简体   繁体   English

清理和验证表单php

[英]Sanitizing and validating form php

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. 完全陷入了困境-PHP的新手,并进行了简单的表单提交(创建帐户页面)以发送到mySQL数据库,因此对问题的宽恕表示歉意。

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. 但是我在插入数据库时​​使用的是PDO和占位符,所以我认为这一方面已经涵盖了。

<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. 这被发送到一个名为createaccount.php的单独的php文件中,该文件运行用户名检查,如果成功运行,则将一个字段发送到我的dbHandler类中的insert函数中的函数。

<?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? 我需要在createaccount.php上运行此功能,因为我无法将其发送到另一个php文件?

Should I be using filter_var? 我应该使用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. 您应该使用PHP正则表达式来严格验证输入数据。

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. 并使用PDO准备阻止您的数据库进行任何形式的SQL注入。

From the PDO::prepare 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. 为将使用不同参数值多次发出的语句调用PDO :: prepare()和PDOStatement :: execute()可通过允许驱动程序协商查询计划的客户端和/或服务器端缓存来优化应用程序的性能,并元信息,并消除了手动引用参数的需要 ,从而有助于防止SQL注入攻击。

I have made an example for you to check and valieded fields before send to server. 我已经为您提供了一个示例,供您在发送到服务器之前检查和设置有效字段。 please have a look. 请看一看。

<script>
function checknull(){
    if(document.getElementById("createUserName").value == ""){
        alert("enter user name");
        return false;
    }

    return true
}
</script>

<form action="createaccount.php" name="form" method="post" onsubmit="return checknull()">

Its not a complete example. 它不是一个完整的例子。 just get you idea how to do the null value check by javascript. 只是让您知道如何通过javascript执行空值检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM