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

时间:2022-12-09 13:50:35

Is it better to validate user input before it's sent to the server with JS or server side with PHP? Or maybe it's worth doing both just to be on the safe side?

在用JS将用户输入发送到服务器之前,验证用户输入是否更好?还是为了安全起见,两种方法都值得?

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? 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? (like e-mail validation to make sure it's in an email format)

我应该说“如果……”else语句直到用户找到正确的语句?或者为用户输入的每个值设置单独的变量,如果正确或错误,将其设置为true或false ?(比如电子邮件验证,确保它是电子邮件格式)

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

有很多方法可以做到,但是你会建议哪一种呢?我不想写50行代码当我能用10行做这个工作的时候…如果这说得通,p

Any help would be appreciated, thanks! :)

如有任何帮助,我们将不胜感激,谢谢!:)

6 个解决方案

#1


8  

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!

所以,如果可能的话,两者都使用。如果您不能/不愿意,那么至少在服务器端执行它。客户端验证是灾难的处方!

#2


5  

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提供了一种同时实现这两种功能的方法。

#3


4  

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.

但是,为了避免向服务器发送带有无效数据的请求,并将响应发送回客户端,最好也进行客户端验证。这会让你的网站反应更迅速。因此,为用户友好添加客户端验证。

#4


0  

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.

因此,在检查客户端时,您只是节省了一点与服务器“交谈”的时间。不要用它来验证你的数据。

#5


0  

Of course you cannot rely just on JavaScript, what if someone has it disabled? 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. Server side is for you own use so as not to have mistakes on your system!

当然,你不能仅仅依靠JavaScript,如果有人禁用了JavaScript怎么办?JavaScript只是为了让站点对用户更友好,并且用户不必每次犯错误时都等待服务器。服务器端是供您自己使用的,以免您的系统出现错误!

#6


0  

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. It's the best way to build forms, also Angular is good and very fast framework for building forms.

您应该在服务器端验证这一点。客户端验证是可选的。您可以声明字段的验证类型,并为您的表单构建通用的验证器。如果您不知道我的意思,请尝试查看AngularJs声明性代码构建。这是构建表单的最好方式,而且棱角很好,构建表单的框架非常快。

http://angularjs.org/

http://angularjs.org/

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

http://docs.angularjs.org/ # ! /食谱/ 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']]:''));
    }

}

}

#1


8  

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!

所以,如果可能的话,两者都使用。如果您不能/不愿意,那么至少在服务器端执行它。客户端验证是灾难的处方!

#2


5  

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提供了一种同时实现这两种功能的方法。

#3


4  

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.

但是,为了避免向服务器发送带有无效数据的请求,并将响应发送回客户端,最好也进行客户端验证。这会让你的网站反应更迅速。因此,为用户友好添加客户端验证。

#4


0  

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.

因此,在检查客户端时,您只是节省了一点与服务器“交谈”的时间。不要用它来验证你的数据。

#5


0  

Of course you cannot rely just on JavaScript, what if someone has it disabled? 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. Server side is for you own use so as not to have mistakes on your system!

当然,你不能仅仅依靠JavaScript,如果有人禁用了JavaScript怎么办?JavaScript只是为了让站点对用户更友好,并且用户不必每次犯错误时都等待服务器。服务器端是供您自己使用的,以免您的系统出现错误!

#6


0  

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. It's the best way to build forms, also Angular is good and very fast framework for building forms.

您应该在服务器端验证这一点。客户端验证是可选的。您可以声明字段的验证类型,并为您的表单构建通用的验证器。如果您不知道我的意思,请尝试查看AngularJs声明性代码构建。这是构建表单的最好方式,而且棱角很好,构建表单的框架非常快。

http://angularjs.org/

http://angularjs.org/

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

http://docs.angularjs.org/ # ! /食谱/ 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']]:''));
    }

}

}