dtz30833 2015-11-11 11:45
浏览 51
已采纳

清理和验证表单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.

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 :)

  • 写回答

2条回答 默认 最新

  • drodsh7940 2015-11-11 12:35
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧