简体   繁体   English

PHP服务器端验证

[英]PHP Server Side Validation

Using various tutorials namely here and here I've managed to put together the following PHP script which performs server side validation on the form being submitted. 通过这里这里的各种教程,我设法将以下PHP脚本组合在一起,该脚本对提交的表单执行服务器端验证。 (I already have script which is dealing with the 'client side' validation. (我已经有了处理“客户端”验证的脚本。

<?php
//email signup ajax call
if($_GET['action'] == 'signup'){

    //sanitize data
    $email = mysql_real_escape_string($_POST['signup-email']);

    //validate email address - check if input was empty
    if(empty($email)){
        $status = "error";
        $message = "You did not enter an email address!";
    }
    else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
            $status = "error";
            $message = "You have entered an invalid email address!";
    }
    else {

            $insertSignup = mysql_query("INSERT INTO signups (signup_email_address) VALUES ('$email')");
            if($insertSignup){ //if insert is successful
                $status = "success";
                $message = "You have been signed up!";  
            }
            else { //if insert fails
                $status = "error";
                $message = "Ooops, Theres been a technical error!"; 
            }

    }

    //return json response
    $data = array(
        'status' => $status,
        'message' => $message
    );

    echo json_encode($data);
    exit;
}
?>

What I'm now trying to do is to add another field, in this case 'name' which I'd like to also validate. 我现在想要做的是添加另一个字段,在这种情况下,我也想验证“姓名”。

The problem I'm having is that I'm not sure how to add another field into the above code. 我遇到的问题是我不确定如何在上述代码中添加另一个字段。 Again, I've been trying to find an example which I could use to study from, but I haven't found any that I can use. 同样,我一直在尝试寻找一个可以用来学习的示例,但是我没有找到可以使用的示例。

I just wondered whether someone could possibly look at this please, and perhaps point me in the right direction. 我只是想知道是否有人可以看看这个,也许会指出正确的方向。

Many thanks and kind regards 非常感谢和问候

PHP has a Filter extension to validate and sanitize input . PHP具有Filter扩展,可以验证和清除输入

The function you are looking for is 您正在寻找的功能是

There is also filter_input_array but since there is no easy way to unit-test that properly, it is easier to use the above one instead and pass it the superglobals as needed. 也有filter_input_array但是由于没有简单的方法可以正确地对它进行单元测试,因此更容易使用上面的方法,并根据需要将其传递给超全局变量。

Example: 例:

$userInput = array(
    'signup-email' => 'foo at example.com',
    'name' => 'ArthurDent42'
);

$validatedInput = filter_var_array(
    $userInput, 
    array(
        'signup-email' => FILTER_VALIDATE_EMAIL,
        'name' => array(
            'filter' => FILTER_VALIDATE_REGEXP,
            'options' => array(
                'regexp' => "/^[a-z ]{5,10}$/i"
            )
        )
    )
);

var_dump($validatedInput);

Output ( demo ): 输出( 演示 ):

array(2) { 
    ["signup-email"]=> bool(false) 
    ["name"]=> bool(false)
}

Once you have the input validated and sanitized put some guard clauses for each of the values in the array and return early when they are false: 验证并清除输入后,为数组中的每个值放置一些保护子句,如果它们为false,则尽早返回:

if (!$validatedInput['signup-email']) {
    return json_encode(array(
        'status' => 'error',
        'message' => 'The eMail was invalid'
    ));
}

if (!$validatedInput['name']) {
    return json_encode(array(
        'status' => 'error',
        'message' => 'Name must be 5 to 10 letters from A to Z only'
    ));
}

// everything's validated at this point. Insert stuff to database now.

Note that you want to use either PDO or mysqli instead of ext/mysql . 注意, 您要使用PDO或mysqli而不是ext / mysql

In your HTML add a field: 在HTML中添加一个字段:

<input type="text" name="name" value="" />

In your PHP: 在您的PHP中:

$name = trim($_POST['name']);

To validate: 验证:

if ($name === '') {
    $status = 'error';
    $message = 'need a name!';
}

Now add name to your insert statement (it would be better to use PDO prepared statements ): 现在将名称添加到您的插入语句中(最好使用PDO准备的语句 ):

$nameSql = mysql_real_escape_string($name);
$insertSignup = mysql_query("INSERT INTO signups (signup_email_address, name) VALUES ('$email', '$nameSql')");
    $rule['email']= '/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$`/'
    $rule['name']= 'bla bla';
    $rule['address']= 'bla bla';

   $data =  sanitize($_POST,$rule);
    function sanitize($input_array,$rule){
    $message = array();
     foreach($input_array as $key=> $value){
     $input_array[$key]= mysql_real_escape_string($value);
     if(isset($rule[$key])){
      if(!preg_match($rule[$key],$input_array[$key]){
        $message[$key] = 'error';
        unset($input_array[$key]);//optional
       }
      }
     }
    return array('data'=>$input_array,'message'=>$message);
    }

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

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