简体   繁体   English

服务器端验证/编程和设计

[英]Server Side Validation/Programming and Design

I have been stuck on this for some time now. 我已经坚持了一段时间。 I have a form that is located in index.php . 我有一个位于index.php的表单。 The data is sent to a php file called, processuserform.php . 数据被发送到名为processuserform.php的php文件中。 I extract all the inputs and assign them each to their own variable. 我提取所有输入并将每个输入分配给它们自己的变量。 Does the following look like it is the proper way to validate and sanitize a form on Server side? 以下内容看起来像是在服务器端验证和清理表单的正确方法吗?

First is the form itself then the PHP file will be used to process the data sent to it. 首先是表单本身,然后将使用PHP文件处理发送给它的数据。

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

processuserform.php processuserform.php

<?php

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

// define variables and set to empty values
$first_nameErr = $last_nameErr = $emailErr = $pwErr = $genderErr = "";
$first_name = $last_name = $email = $pw = $gender = "";

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
    if (empty($_POST["firstname"]))
    {
        $first_nameErr = "Name is required";
    }
    else
    {
        $first_name = test_input($_POST["firstname"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$first_name))
        {
            $first_nameErr = "Only letters and white space allowed";
        }
    }

    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
        if (empty($_POST["lastname"]))
        {
            $last_nameErr = "Name is required";
        }
        else
        {
            $last_name = test_input($_POST["lastname"]);
            // check if name only contains letters and whitespace
            if (!preg_match("/^[a-zA-Z ]*$/",$last_name))
            {
                $last_nameErr = "Only letters and white space allowed";
            }
        }

        if (empty($_POST["Email"]))
        {
            $emailErr = "Email is required";
        }
        else
        {
            $email = test_input($_POST["email"]);
            // check if e-mail address syntax is valid
            if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
            {
                $emailErr = "Invalid email format";
            }
        }

        if (empty($_POST["Password"]))
        {
            $pwErr = "Password is required";
        }
        else
        {
            $pw = test_input($_POST["Password"]);
        }
    }
    if (empty($_POST["Gender"]))
    {
        $genderErr = "Gender is required";
    }
    else
    {
        $gender = test_input($_POST["Gender"]);
    }
}

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

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

$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', '$pw', '$gender')");
mysqli_close($db_conx);

header("Location: not/important.php")
?>

Thanks all for your help. 感谢你的帮助。 If I am sanitizing it and validating it wrong would someone mind giving me an example of how it should look using one of my inputs as an example? 如果我要对它进行消毒和验证是错误的,有人会介意以我的一项输入为例,给我一个示例,以显示它的外观吗? I could use help as this is a bit confusing. 我可以使用帮助,因为这有点令人困惑。 Thanks again! 再次感谢!

You definitely want the validation server-side (doing validation in javascript does not protect your data at all!) In any case you should let the user enter form data, POST that, validate it and if there are errors get your php to re-write the form with existing data filled in (so the user doesn't have to enter it again) and messages against the entries with an error. 您一定要在服务器端进行验证(在javascript中进行验证完全不能保护您的数据!)无论如何,您应该让用户输入表单数据,对其进行发布,验证,如果有错误,请让您的php重新使用现有数据填写表单(这样用户就不必再次输入表单),并针对出现错误的条目写消息。

ie something like: (much simplified!) 即类似:(简化很多!)

echo '<input id="firstname" value="' . $first_name . '"/>';
if( $first_nameErr != "" )
   echo 'Error: '.$first_nameErr;

Yours, TonyWilk 您的托尼·威尔克(TonyWilk)

Javascript validation is good but only for UI purpose, because a user can bypass that validation as javascript is client based. Javascript验证很好,但仅用于UI目的,因为用户可以绕过该验证,因为javascript是基于客户端的。

For javascript disabled, i will follow Kuroi Neko as he explained well. 对于禁用了javascript的人,我会按照Kuroi Neko的解释做得很好。

Regarding to php side validation and javascript validation, you can keep both, it will be not a problem. 关于php端验证和javascript验证,您可以同时保留两者,这不是问题。 But in today good practices, i think you should work with ajax based forms which is a good option and also you will have no need to repopulate your forms if an error occurred (I am considering that javascript is always enabled). 但是在今天的良好实践中,我认为您应该使用基于Ajax的表单,这是一个不错的选择,而且如果发生错误,您也无需重新填充表单(我考虑到始终启用javascript)。

You will have to do all your validation at server side in php code which can't be bypassed by a user. 您将必须在服务器端使用无法被用户绕过的php代码进行所有验证。 After the form is submitted by ajax, you validate all the form fields there. 由ajax提交表单后,您将在此验证所有表单字段。 If there is an error, then return errors messages to ajax request and display them. 如果有错误,则将错误消息返回给ajax请求并显示它们。 If there are no errors, then do what ever you want to do with the form data and then return a success message to ajax request. 如果没有错误,请对表单数据执行任何操作,然后将成功消息返回给ajax请求。

Based on the returned message(s) to ajax request, you can do what ever you want, display errors / success messages, redirect user to another page after success, or just hide the form and display the success message. 根据返回给ajax请求的消息,您可以执行所需的任何操作,显示错误/成功消息,在成功后将用户重定向到另一个页面,或者仅隐藏表单并显示成功消息。

For ajax form submission, i will suggest you use JQuery Form plugin . 对于ajax表单提交,我建议您使用JQuery Form plugin It is very easy to use and support different data types like json, xml and html. 它非常容易使用和支持json,xml和html等不同的数据类型。 On the example page, then have listed working codes, so you can easily adopt it. 在示例页面上,然后列出了工作代码,因此您可以轻松地采用它。

You did not show your JavaScript validation code. 您没有显示JavaScript验证代码。

Trouble is, you will perform the same checks first in JavaScript and then in PHP. 麻烦的是,您将首先在JavaScript中然后在PHP中执行相同的检查。 If for some reason the validation functions don't match, the result might be inconsistent. 如果由于某些原因验证功能不匹配,则结果可能不一致。

My advice is: 我的建议是:

1) if you are not planning to support browsers with JavaScript disabled, simply drop the PHP validation 1)如果您不打算支持禁用JavaScript的浏览器,只需删除PHP验证

2) if you want to support no-script browsers, you should detect that JS is disabled and warn the user that the form might be rejected after validation (it can be really frustrating to fill-in a long form only to get an error after submitting it) 2)如果您要支持无脚本浏览器,则应检测到JS已禁用,并警告用户该表单在验证后可能会被拒绝(填写长表单只会让您在以后输入错误而感到沮丧。提交)

If you support both validations simultaneously, you should make your best efforts to have symetrical validation code, using the same regexps and doing the checks in the same order. 如果同时支持两个验证,则应尽最大努力获得对称验证代码,使用相同的正则表达式并以相同的顺序进行检查。

It is not easy to share code between JS and PHP, but you could design a common format to validate the fields and have a JS and PHP validation engine use the same field definitions. 在JS和PHP之间共享代码并不容易,但是您可以设计一种通用格式来验证字段,并使JS和PHP验证引擎使用相同的字段定义。
That would be the most consistent approach, but it's a lot of work, so if you only have a single form to validate it might not be worth the effort. 那将是最一致的方法,但这需要大量工作,因此,如果您只有一个表单来进行验证,则可能不值得付出努力。

EDIT: to answer your additional remarks and questions 编辑:回答您的其他评论和问题

For ease of use, it is much better to have JavaScript check form data on the fly. 为了易于使用,最好让JavaScript动态检查表单数据。 It allows the user to know all proper informations have been entered before submitting the form. 它允许用户在提交表格之前知道已经输入了所有正确的信息。
PHP validation would produce an error page and force the user to go back to the form page, and (depending on the browser) possibly retype the whole set of informations unless you added some PHP code to fill the fields with previous values. PHP验证将产生一个错误页面,并迫使用户返回到表单页面,并且(取决于浏览器)可能会重新输入整个信息集,除非您添加了一些PHP代码以用以前的值填充字段。

You should resort to PHP validation only if JavaScript is disabled or if you want to prevent malicious submissions (ie some hacker simulating a post request without using your form). 仅当禁用JavaScript或想要防止恶意提交时(即某些黑客在不使用表单的情况下模拟发布请求),才应诉诸PHP验证。

About supporting no-script browsers, I would say 90% of modern sites won't work properly (or offer a poor user experience) with JavaScript and/or cookies disabled, so that would not be such a big deal IMHO. 关于支持无脚本浏览器,我想说90%的现代站点在禁用JavaScript和/或cookie的情况下将无法正常运行(或提供较差的用户体验),所以恕我直言,这不是什么大问题。
It all depends what kind of audience you're targeting. 这完全取决于您所针对的受众。

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

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