处理,验证和清理数据 [英] Processing, validating, and sanitizing data

查看:108
本文介绍了处理,验证和清理数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我一直在这个问题上停留了一段时间。我有一个表格。该表格在index.php中。
我将表单数据发送到名为processuserform的php文件。我提取所有输入并将它们分配给各自的变量。然后,我接受每个变量并通过一个函数来运行它们,我相信这些函数会修剪并去除任何不需要的字符的输入。在同一个函数中,我将任何特殊字符转换为它们的HTML表单。接下来我尝试验证电子邮件。我为此使用了PHP过滤器。我对许多事情不确定,并且一直在寻找相当一段时间来寻求答案,或者至少有一条路要走,所以我可以学习如何正确地对信息进行净化和验证。我的印象是,我需要对待不同于其他所有内容的密码,并且在我学会了如何验证和清理信息之后才会知道。你在下面看到的是我从网上收集的各种资料,这可能最终成为设计网页的不正确方式。我已经使用JavaScript实现了客户端验证,但对我的网站感到恐惧,因为我没有进行服务器端验证。如果有人关闭了javascript,会输入错误的信息会发生什么?他们如何被送回注册部门并告诉他们犯了一个错误。当他们错误地输入信息时,我不希望人们导致空白屏幕。我只想让我的网站在服务器端进行验证。我从字面上一直试图学习3个月。这并不是说我不聪明,但却无法找到一个可行的方法去做这件事。有很多方法让我很困惑,不知道下一步该做什么。我会在下面留下我的代码,希望你们对我有同情心和耐心。提前致谢。

  ====================== ================================================== == 
表格
======================================= ===================================
< form method =POSTname =注册action =php / processuserform.php>

< input id =firstnameonkeyup =validateFirstName()placeholder =First Name
type =text/>< label id =firstnameprompt> ;< /标签>

< br>< br>

< input id =lastnameonkeyup =validateLastName()placeholder =Last Name
type =text/>
< label id =lastnameprompt>< / label>

< br>< br>

$ b< input id =Emailonkeyup =validateEmail()placeholder =Emailtype =text/>< label
id = Emailprompt>< /标签>

< br />< br />

< input id =Passwordonkeyup =validatePassword()placeholder =Create Password
type =password/>< label id =Passwordprompt> ;< /标签>

< br />< br />


< strong>男性< / strong>< input id =Gendertype =radioname =sexvalue =male>
< strong>女性< / strong>< input id =Gendertype =radioname =sexvalue =female>

< br />< br />

如果您同意< a href =#>条款与条件,请点击提交< / a>
< br>
< input id =submitonclick =return validateUserRegistration()value =Submit
type =submitname =submit/>< label id =submitprompt >< /标签>

< br />< br />
< hr>
< / form>





========================== ==========================================
//我如何正在处理它。
============================================== ======================


<?php

// == ==================================
//变量

$ first_name = check_input($ _ POST ['firstname']);
$ last_name = check_input($ _ POST ['lastname']);
$ email = check_input($ _ POST ['Email']);
$ password = check_input($ _ POST ['Password']);
$ gender = check_input($ _ POST ['Gender');

// ====================================
//修剪并删除名字

函数check_input($ first_name)
{
$ first_name = trim($ first_name);
$ first_name = stripslashes($ first_name);
$ first_name = htmlspecialchars($ first_name);
返回$ first_name; };

// ====================================
//修剪并删除姓氏

函数check_input($ last_name)
{
$ last_name = trim($ last_name);
$ last_name = stripslashes($ last_name);
$ last_name = htmlspecialchars($ last_name);
返回$ last_name; };

// ====================================
//修剪并剥离电子邮件

函数check_input($ email)
{
$ email = trim($ email);
$ email = stripslashes($ email);
$ email = htmlspecialchars($ email);
返回$ email; };

// =====================================
//修剪并删除密码

函数check_input($ password)
{
$ password = trim($ password);
$ password = stripslashes($ password);
$ password = htmlspecialchars($ password);
返回$ password; };
// ======================================
//修剪和剥离性别
功能check_input($ gender)
{
$ gender = trim($ gender);
$ gender = stripslashes($ gender);
$ gender = htmlspecialchars($ gender);
返回$ gender; };

// ======================================== =================
//验证电子邮件

$电子邮件

if(filter_var($ email, FILTER_VALIDATE_EMAIL))
{
echo'这应该是一个有效的电子邮件';
}
else
{
echo'你需要一些指导':
}


// ==== ================================================== ==


$ hostname =这是正确的;
$ username =这是正确的;
$ password =这是对的;
$ dbname =这是正确的;

$ db_conx = mysqli_connect($ hostname,$ username,$ password)或DIE(无法
连接数据库!请稍后再试。);

if(mysqli_connect_errno()){
echo mysqli_connect_error();
exit();
}

$ select = mysqli_select_db($ db_conx,$ dbname);

mysqli_query($ db_conx,INSERT INTO users(firstname,lastname,email,password,
gender)
VALUES('$ first_name','$ last_name','$电子邮件','$密码','$性别'));
mysqli_close($ db_conx);

header(Location:pages / profile.php)
?>


解决方案

当您从所有的用户输入的变量,您现在也必须验证它们!



从我以前学到的知识来看,您作为开发人员应该具备的假设之一是永远不会相信所有用户都知道表单的正确输入!永远不要相信用户!所以考虑到这一点,我们去验证服务器端。



最简单的验证就是确保用户输入的数据可以工作(我不知道正确的方法来放置它)以保持应用程序的质量。



让我们以您的一个变量为例。

  $ email 

好的,你做了验证以检查它是否是电子邮件,但是有更好的方法来验证它,并且还需要检查其他因素,例如用户是否输入了空格等。

 函数validateEmail($ email)
{
// Regex是验证电子邮件的好方法。这将检查它是否有一个@符号以及电子邮件的长度。
if(!preg_match(/ ^ [^ @] {1,64} @ [^ @] {1,255} $ /,$ email))
{
//电子邮件无效因为某一节中的字符数量错误,或@符号数量错误。
返回false;
}
//检查输入是否是空白以外的内容。
//即使您在html中输入required文本字段,空白仍然是一个有效的输入,因此您最好检查以确保用户不允许输入空的字段!
if(!preg_match(/ ^ [a-zA-Z] * $ /,$ email))
{
return false;
}
返回true;
}

这只是您如何使用正则表达式验证电子邮件的例子。

您甚至可以验证域名是否为真实域名,或者您可以验证电子邮件中是否包含任何亵渎字词等。关键是要知道你不想进入你的系统。



确保你也清理你的查询,以避免任何攻击。 b
$ b

希望这种帮助!



干杯!


Ok I have been stuck on this for some time now. I have a form. The form is in "index.php". I send the form data to a php file called, "processuserform". I extract all the inputs and assigned them each to their own variable. I then took each variable and ran them through a function that I believe trims and strips the input from any unwanted characters. Within the same function I transformed any special characters into their HTML forms. Next I tried to validate the email. I used a PHP filter for this. I am uncertain on many things and have been searching for quite some time for an answer or at least a path to follow so I can learn how to properly sanitize and validate information. I am under the impression I will need to treat passwords different then everything else and will learn that after I learn how to validate and sanitize information. What you see below is what I have gathered from various sources on the net, which may end up being an incorrect way of designing a web page. I have achieved client side validation using Javascript but am fearful for my site because I do not have server side validation up. What happens if someone, who has javascript turned off, enters the wrong kind of information? How do they get sent back to the registration part and told they have made a mistake. I dont want people being led to a blank screen when they incorrectly enter information. I just want my site to be validated on the server side. I have literally been trying to learn this for 3 months. It is not that I am unintelligent but cannot find a set way to go about doing this. With so many ways I am confused ast to the path to take and what to do next. I will leave my code below and hopefully you guys will have compassion and patience for me. Thanks in advance.

 ==========================================================================
  Form
 ==========================================================================
 <form method="POST" name="signup" action="php/processuserform.php">

 <input id="firstname" onkeyup="validateFirstName()"  placeholder="First Name" 
 type="text" /><label id="firstnameprompt"></label>

 <br><br>

 <input id="lastname" onkeyup="validateLastName()"  placeholder="Last Name" 
 type="text"/>
 <label id="lastnameprompt"></label>

 <br><br>


 <input id="Email" onkeyup="validateEmail()"  placeholder="Email" type="text" /><label 
 id="Emailprompt"></label>

 <br /><br />

 <input id="Password" onkeyup="validatePassword()"  placeholder="Create Password" 
 type="password" /><label id="Passwordprompt"></label>

 <br /><br />


 <strong>Male</strong><input id="Gender" type="radio" name="sex" value="male">
 <strong>Female</strong><input id="Gender" type="radio" name="sex" value="female">

 <br /><br />

 Click "Submit" if you agree to <a href="#">"Terms And Conditions"</a>
 <br>
 <input id="submit" onclick="return validateUserRegistration()" value="Submit" 
 type="submit" name="submit"/><label id="submitprompt"></label>

 <br /><br />
 <hr>
 </form> 





 ====================================================================
  //How I am Processing it.
 ====================================================================


 <?php

 //====================================
 //Variables

 $first_name= check_input($_POST['firstname']);
 $last_name= check_input($_POST['lastname']);
 $email= check_input($_POST['Email']);
 $password= check_input($_POST['Password']);
 $gender= check_input($_POST['Gender');

 //====================================
 //Trim and strip first name

 function check_input($first_name)
 { 
 $first_name = trim($first_name);
 $first_name = stripslashes($first_name);
 $first_name = htmlspecialchars($first_name);
 return $first_name; }; 

 //====================================
 //Trim and strip last name

 function check_input($last_name)
 { 
 $last_name = trim($last_name);
 $last_name = stripslashes($last_name);
 $last_name = htmlspecialchars($last_name);
 return $last_name; }; 

 //====================================
 //Trim and strip email

 function check_input($email)
 { 
 $email = trim($email);
 $email = stripslashes($email);
 $email = htmlspecialchars($email);
 return $email; }; 

 //=====================================
 //Trim and Strip Password

 function check_input($password)
 { 
 $password = trim($password);
 $password = stripslashes($password);
 $password = htmlspecialchars($password);
 return $password; }; 
 //======================================
 //Trim and strip Gender
 function check_input($gender)
 { 
 $gender = trim($gender);
 $gender = stripslashes($gender);
 $gender = htmlspecialchars($gender);
 return $gender; }; 

 //=========================================================
 //Validate Email

 $email

 if(filter_var($email,FILTER_VALIDATE_EMAIL))
 {
 echo 'This should be a valid email';
 }
 else
 {
 echo 'You need some guidance':
 }


 //========================================================


  $hostname="this is right";
  $username="this is right";
  $password="this is right";
  $dbname="this is right";

   $db_conx = mysqli_connect($hostname, $username, $password) OR DIE ("Unable to
  connect to database! Please try again later.");

  if(mysqli_connect_errno()){
  echo mysqli_connect_error();
  exit();
  }

  $select = mysqli_select_db($db_conx,$dbname);

  mysqli_query($db_conx,"INSERT INTO users (firstname, lastname, email, password, 
  gender)
  VALUES ('$first_name', '$last_name', '$email', '$password', '$gender')");
  mysqli_close($db_conx);

  header("Location: pages/profile.php")
  ?>

解决方案

Well after you removed the unwanted characters from all of your user inputted variables, you now have to validate them as well!

From what I have learned in the past, one of the assumptions you should have as a developer is to NEVER trust that all users know the correct inputs for forms! Never trust the user! So with that in mind, we go and validate server side.

Validation in simplest terms is just making sure that the user inputs data that will work (I don't know the right way to put it) in a way to maintain the quality of your application.

Let's take one of your variables for example.

$email

Okay, you did a validation to check if it's an email, but there are better ways to validate it and you also need to check for other factors such as if the user inputs a blank space etc.

function validateEmail($email) 
    {
    //Regex is a great way to validate email. This checks if it has one @ sign and also the lengths of the email.
        if (!preg_match("/^[^@]{1,64}@[^@]{1,255}$/", $email)) 
            {
        // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
                return false;
            }
//check if the input was something other than a whitespace.
//Even if you put inside the textfield "required" in html, a whitespace will still be a   //valid input so you better check to make sure that users aren't allowed to enter empty //fields!
         if (!preg_match("/^[a-zA-Z ]*$/",$email))
            {
                return false;
            }
        return true;
    }

This is just an example of how you can validate email using Regular Expressions.

You can even validate whether or not the domain is a real domain, or you can validate if the email contains any profane words and such. The key is to know what you don't WANT going into your system.

Make sure you also sanitize your queries in order to avoid any attacks.

Hope this sort of helps!

Cheers!

这篇关于处理,验证和清理数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆