简体   繁体   English

用户输入验证,客户端还是服务器端? [PHP / JS]

[英]User input validation, client-side or server-side? [PHP/JS]

Is it better to validate user input before it's sent to the server with JS or server side with PHP? 在使用JS或服务器端使用PHP发送到服务器之前验证用户输入是否更好? Or maybe it's worth doing both just to be on the safe side? 或者,为了安全起见,这两个值得做两件事吗?

I'm creating a site (very simple at the moment) that has a members area/admin area/etc. 我正在创建一个拥有会员区/管理区/等的网站(目前非常简单)。 At the moment i only have user input of Username and Password, in the future there will be more (email, address, etc), but whats the best practice of checking the data? 目前我只有用户输入的用户名和密码,将来会有更多(电子邮件,地址等),但最新的检查数据的做法是什么?

Do i throw a load of 'if...else' statements at it until the user gets it right? 我是否会在其中抛出一堆'if ... else'语句,直到用户正确使用它为止? Or maybe have separate variables for each value entered by the user and set it to true or false if it's correct or wrong? 或者可能为用户输入的每个值都有单独的变量,如果正确或错误,则将其设置为true或false? (like e-mail validation to make sure it's in an email format) (如电子邮件验证,以确保它是电子邮件格式)

There are a lot of ways to do it, but which ones you would suggest? 有很多方法可以做到,但你会建议哪些方法? I don't want to be writing 50 lines of code when i could do the job in 10 lines...if that makes sense :p 我不想写10行代码,当我可以完成10行代码时......如果这样做有意义:p

Any help would be appreciated, thanks! 任何帮助将不胜感激,谢谢! :) :)

Server-side validation is a must , client-side validation is a plus . 服务器端验证是必须的 ,客户端验证是一个加号

If you only use client-side validation, nefarious people will hack your system to post un-validated stuff - breaking your scripts, and potentially exploiting your system. 如果你只使用客户端验证,那些邪恶的人会破解你的系统发布未经验证的东西 - 破坏你的脚本,并可能利用你的系统。 This is very bad from a security standpoint. 从安全角度来看,这是非常糟糕的

That said, you should also include client-side validation, since that's much quicker than a round trip to the server, and gives your users instant feedback. 也就是说,您还应该包括客户端验证,因为这比往返服务器要快得多,并为您的用户提供即时反馈。 This'll keep your users happy, and will have them coming back to your site. 这将让您的用户满意,并让他们回到您的网站。

So, if possible, use both . 因此,如果可能,请同时使用两者 If you can't/won't, then at least do it server-side. 如果你不能/不会,那么至少在服务器端做。 Client-side-only validation is a recipe for disaster! 仅客户端验证是灾难的秘诀!

Do both. 做到这两点。

Client side gives the responsiveness users expect and server side protects your data. 客户端提供用户期望的响应能力,服务器端保护您的数据。

I'm sure PHP has some libraries that would help you much like what ASP.NET MVC does to provide a way of doing both in one step. 我确信PHP有一些库可以帮助你,就像ASP.NET MVC提供的一种方法一样。

Input validation should certainly happen at the server side for safety reasons. 出于安全原因,输入验证当然应该在服务器端进行。

However, to avoid sending a request to the server with invalid data and send the response back to the client, it is nice to have client-side validation as well. 但是,为了避免向服务器发送包含无效数据的请求并将响应发送回客户端,也可以进行客户端验证。 This will make your website more responsive. 这将使您的网站更具响应性。 So add client-side validation for user-friendliness. 因此,为了用户友好性添加客户端验证。

Validation, ALWAYS server side. 验证,总是服务器端。 I can tamper with your form client-side and fill in crazy values and still get validated. 我可以篡改您的表单客户端并填写疯狂的值,仍然得到验证。 I can't tamper with server-side scripts. 我无法篡改服务器端脚本。

So when checking client-side, you're just saving a little time 'talking' with the server. 因此,在检查客户端时,您只需节省一点时间与服务器“交谈”。 Never use it to validate your data for real. 切勿使用它来验证您的数据是否真实。

Of course you cannot rely just on JavaScript, what if someone has it disabled? 当然你不能仅仅依靠JavaScript,如果有人禁用它会怎么样? JavaScript is only to make the site more user friendly for the user and that he does not have to wait the server each time he makes a mistake. JavaScript只是为了让网站对用户更友好,并且每次出错时都不必等待服务器。 Server side is for you own use so as not to have mistakes on your system! 服务器端供您自己使用,以免在您的系统上出错!

You should validate this on server-side. 您应该在服务器端验证这一点。 The client-side validation is optional. 客户端验证是可选的。 You can declare types of validation for fields, and build generic validator for your forms. 您可以声明字段的验证类型,并为表单构建通用验证器。 If you don't know what i mean try looking at AngularJs declarative code building. 如果您不知道我的意思,请尝试查看AngularJs声明性代码构建。 It's the best way to build forms, also Angular is good and very fast framework for building forms. 这是构建表单的最佳方式,Angular也是构建表单的良好且非常快速的框架。

http://angularjs.org/ http://angularjs.org/

http://docs.angularjs.org/#!/cookbook/advancedform http://docs.angularjs.org/#!/cookbook/advancedform

Look at this lines: 看看这一行:

<input type="text" name="form.address.line1" size="33" ng:required/> <br/>
    <input type="text" name="form.address.city" size="12" ng:required/>,
    <input type="text" name="form.address.state" size="2" ng:required ng:validate="regexp:state"/>
    <input type="text" name="form.address.zip" size="5" ng:required
  validate="regexp:zip"/>

For your server side you can also define some structure, which will contain form fields, validation methods, and error string for each field. 对于服务器端,您还可以定义一些结构,其中包含每个字段的表单字段,验证方法和错误字符串。 Then in loop, validate each field based on your information structure. 然后在循环中,根据您的信息结构验证每个字段。 You can easily manage forms builded that way. 您可以轻松管理以这种方式构建的表单。

Example in PHP: PHP中的示例:

Form data: 表格数据:

$formData = array (
    array(
     'ID' => "name",
     'validate' => '/.+/',
     'label' => 'Your name',
     'errorMsg' => "This field is required",
     'type' => 'text' 
    ),
 array(
         'ID' => "Phone number",
         'validate' => '/^[0-9+ ]+$/',
         'label' => 'Numer telefonu',
         'errorMsg' => "Please provide proper telephone number",
         'type' => 'text'
        )
);

Validator and form generator (sorry for simple and messy code here): 验证器和表单生成器(对不起这里的简单和杂乱的代码):

$s = '';
foreach ($formData as $input){
    $s .= sprintf('<label for="%s">%s</label>',$input['ID'],$input['label']);
    if (isset($_POST[$input['ID']]) && !empty($input['validate']) && !preg_match($input['validate'],$_POST[$input['ID']])){
        $error = true;
         $s .= sprintf('<div class="formErrorValidate">%s</div>',$input['errorMsg']);
    }
    if (isset($_POST[$input['ID']])) $htmlMsg = str_replace('%'.$input['ID'].'%',$_POST[$input['ID']],$htmlMsg);
    if ($input['type'] == 'textarea'){
        $s .= sprintf('<textarea name="%s" id="%s">%s</textarea>',$input['ID'],$input['ID'],(isset($_POST[$input['ID']])?$_POST[$input['ID']]:''));
    } else {
        $s .= sprintf('<input type="%s" name="%s" id="%s" value="%s"/>',$input['type'],$input['ID'],$input['ID'],(isset($_POST[$input['ID']])?$_POST[$input['ID']]:''));
    }

} }

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

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