净化和验证表单php [英] Sanitizing and validating form php

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

问题描述

完全抛出深层 - PHP新手,做一个简单的表单提交(创建帐户页面)发送到mySQL数据库,以便道歉的问题noobness。



我不确定如何在发送之前正确验证和清理数据。
但是我在插入数据库时​​使用了一个PDO和占位符,所以我想我已经覆盖了这一面。

  < form action =createaccount.phpname =formmethod =post> 
< input type =textname =createUserNameid =createUserNameplaceholder =User Name>< br>
< input type =passwordname =passWordid =passWordplaceholder =Password(Min 6 Characters)>< br>
< input type =passwordname =confirmPWid =confirmPWplaceholder =确认密码>< br>

< input type =textname =fNameid =fNameplaceholder =First Name>< br>
< input type =textname =sNameid =sNameplaceholder =Surname>< br>< br>

< input type =emailname =userEmailid =userEmailplaceholder =Email Address>< br>
< input type =submitvalue =Create Account>
< / form>

发送到一个名为createaccount.php的独立php文件,该文件运行用户名检查,如果成功运行

 <?php 
session_start()函数将字段发送到我的dbHandler类中的插入函数中。 ;
include('connect.php');

$ username = $ _POST ['createUserName'];
$ password = $ _POST ['passWord'];
$ password_confirm = $ _POST ['confirmPW'];
$ firstname = $ _POST ['fName'];
$ surname = $ _POST ['sName'];
$ email = $ _POST ['userEmail'];

if($ dbh-> checkUserName($ username)){
$ _SESSION ['message'] =用户名已被占用,请重试;
header('Location:createAccount.php');
exit();
} else {
$ dbh-> createAccount($ username,$ password,$ password_confirm,$ firstname,$ surname,$ email);
header('Location:login.php');
exit();
};

?>

所以我的问题是。我应该使用

 <?php echo htmlspecialchars($ _ SERVER [PHP_SELF]);?> 

在我的表单动作中?如果是这样。我需要在createaccount.php这里运行函数,因为我不能将它发送到另一个php文件?



我应该使用filter_var吗?和/或我应该使用修剪,strips strips或任何在我的变量发送到表单中?我该怎么做呢?我的理解是:
$ b $

  $ name = test_input($ _ POST ['createUserName']); 
$ password = test_input($ _ POST ['passWord']); .. etc

函数test_input($ data){
$ data = trim($ data);
$ data = stripslashes($ data);
$ data = htmlspecialchars($ data);
返回$ data;
}

另外,这里是我的插入函数。这是安全/正确写入?

 <?php 
函数createAccount($ userName,$ pw,$ confirmPW ,$ fName,$ sName,$ email){
$ sql =插入`room_project`.`user`(`userName`,`pass`,`confirmPW`,`fName`,`sName`,``电子邮件`)VALUES(?,?,?,?,?,?);;
$ query = $ this-> connection-> prepare($ sql);
$ query-> execute(Array($ userName,$ pw,$ confirmPW,$ fName,$ sName,$ email));

}

?>

我非常感谢任何建议!再次请原谅这个初学者的本质:)

/manual/en/function.preg-match.phprel =nofollow> PHP正则表达式来严格验证您的输入数据。



假设您要验证以下输入字段,


  • 用户名

    li>
  • 密码

  • 名字

  • li>


然后你会这样做,

  if(isset($ _ POST ['submit'])&&!empty($ _ POST ['submit'])){

//使用布尔变量来跟踪错误
$ error = false;

//用户名验证
$ username = trim($ _ POST ['username']);
$ username_pattern =/ ^ [a-zA-Z0-9] {3,15} $ /; //用户名应该只包含字母和数字,长度应该在3到15个字符之间
if(preg_match($ username_pattern,$ username)){
// success
} else {
//错误
$ error = true;
}

//密码验证
$ password = $ _POST ['password'];
$ confirm_password = $ _POST ['confirm_password'];
if(strlen($ password)> = 6&& $ password === $ confirm_password){//密码的长度应该大于或等于6
// success
} else {
//错误
$ error = true;
}

//名字验证
$ first_name = trim($ _ POST ['first_name']);
$ first_name_pattern =/ ^ [a-zA-Z] {2,15} $ /;
if(preg_match($ first_name_pattern,$ first_name)){//第一个名字只能包含字母和长度应该在2到15个字符之间
//成功
} else {
//错误
$ error = true;
}


//姓氏验证
$ last_name = trim($ _ POST ['last_name']);
$ last_name_pattern =/ ^ [a-zA-Z] {2,15} $ /;
if(preg_match($ last_name_pattern,$ last_name)){//姓氏只能包含字母和长度应该在2到15个字符之间
//成功
} else {
//错误
$ error = true;
}

//电子邮件验证
$ email = trim()
$ email_pattern =/^([a-z0-9\._\ + \ - ] {3,30})@([A-z0-9\ - 。] {2,30})((\([AZ] {2,20})){1,3} )$ /;
if(preg_match($ email_pattern,$ email)){//验证电子邮件地址
//成功
} else {
//错误
$ error = true ;
}

if(!$ error){
//所有字段都经过验证。现在执行你的数据库操作。
} else {
//显示错误消息
}
}

并使用 PDO准备来防止您的数据库受到任何形式的SQL注入。



PDO ::准备


对于将使用不同参数值多次发布的语句,调用PDO :: prepare()和PDOStatement :: execute()可以通过允许驱动程序协商查询计划的客户端和/或服务器端缓存来优化应用程序的性能,元信息和通过消除手动引用参数的需要来帮助防止SQL注入攻击。


Completely thrown in the deep end - new to PHP and doing a simple form submission (create account page) to send to a mySQL database so apologies for the noobness of question.

I'm not sure how to properly validate and sanitize the data before sending it. But i am using a PDO and placeholders when inserting into the database so I think i have that side covered.

<form action="createaccount.php" name="form" method="post">
    <input type="text" name="createUserName" id="createUserName" placeholder="User Name"><br>
    <input type="password" name="passWord" id="passWord" placeholder="Password (Min 6 Characters)"><br>
    <input type="password" name="confirmPW" id="confirmPW" placeholder="Confirm Password"><br>

    <input type="text" name="fName" id="fName" placeholder="First Name"><br>
    <input type="text" name="sName" id="sName" placeholder="Surname"><br><br>

    <input type="email" name="userEmail" id="userEmail" placeholder="Email Address"><br>
    <input type="submit" value="Create Account">
</form>

This is sent to a seperate php file called createaccount.php which runs a username check and if success runs a function that sends the fields into an insert function in my dbHandler class.

<?php 
session_start();
include('connect.php'); 

  $username = $_POST['createUserName'];
  $password = $_POST['passWord'];
  $password_confirm = $_POST['confirmPW'];
  $firstname = $_POST['fName'];
  $surname = $_POST['sName'];
  $email = $_POST['userEmail'];

  if ($dbh->checkUserName($username)) {
    $_SESSION['message'] = "Username is taken, please try again";
    header('Location: createAccount.php');
  exit();
  } else {
    $dbh->createAccount($username, $password, $password_confirm, $firstname, $surname, $email);
    header('Location: login.php');
    exit();
  };

 ?>

So my questions are. Should i be using

<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>

In my form action? If so. I will need to run the function on createaccount.php here yes as I cant send it to another php file?

Should I be using filter_var? And/Or Should I be using trim, stripslashes or anything in my variables im sending into the form? How do I do this? My understanding is

$name = test_input($_POST['createUserName']);
$password = test_input($_POST['passWord']); .. etc

function test_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
return $data;
}

Also, here is my insert function. Is this secure/written correctly?

<?php 
function createAccount($userName, $pw, $confirmPW, $fName, $sName, $email) {
        $sql = "INSERT INTO `room_project`.`user` (`userName`, `pass`, `confirmPW`, `fName`, `sName`, `email`) VALUES (?, ?, ?, ?, ?, ?);";
        $query = $this->connection->prepare($sql);
        $query->execute(Array($userName, $pw, $confirmPW, $fName, $sName, $email));

    }

?>

I thoroughly appreciate any advice! Again please excuse the beginner nature of this :)

解决方案

You should use PHP regex to strictly validate your input data.

Suppose you want to validate the following input fields,

  • Username
  • Password
  • First name
  • Last name
  • Email

then you would do something like this,

if(isset($_POST['submit']) && !empty($_POST['submit'])){

    // use a boolean variable to keep track of errors
    $error = false;

    // Username validation
    $username = trim($_POST['username']);
    $username_pattern = "/^[a-zA-Z0-9]{3,15}$/"; // username should contain only letters and numbers, and length should be between 3 and 15 characters
    if(preg_match($username_pattern, $username)){
        // success
    }else{
        // error
        $error = true;
    }

    // Password validation
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    if(strlen($password) >= 6 && $password===$confirm_password){ // length of the password should be greater than or equal to 6
       // success
    }else{
       // error
       $error = true;
    }

    // First name validation
    $first_name = trim($_POST['first_name']);
    $first_name_pattern = "/^[a-zA-Z]{2,15}$/";
    if(preg_match($first_name_pattern, $first_name)){ // first name should contain only letters and length should be between 2 and 15 characters
        // success
    }else{
        // error
        $error = true;
    }


    // Last name validation
    $last_name = trim($_POST['last_name']);
    $last_name_pattern = "/^[a-zA-Z]{2,15}$/";
    if(preg_match($last_name_pattern, $last_name)){ // last name should contain only letters and length should be between 2 and 15 characters
        // success
    }else{
        // error
        $error = true;
    }

    // Email validation
    $email = trim()
    $email_pattern = "/^([a-z0-9\._\+\-]{3,30})@([a-z0-9\-]{2,30})((\.([a-z]{2,20})){1,3})$/";
    if(preg_match($email_pattern, $email)){ // validate email addresses
        // success
    }else{
        // error
        $error = true;
    }

    if(!$error){
        // all fields are validated. Now do your database operations.
    }else{
        // display error message
    }
}

And use PDO prepare to prevent your database from any kind of SQL Injection.

From the PDO::prepare

Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.

这篇关于净化和验证表单php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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