代码之家  ›  专栏  ›  技术社区  ›  csandreas1

PHP验证多个必需的输入字段

php
  •  0
  • csandreas1  · 技术社区  · 6 年前

    在发送电子邮件之前,我正在验证一些输入字段。我使用for each来更快地遍历数组,并检查每个输入都不是空的,并在jquery中将其作为响应返回以显示错误。问题是 email message

    数组元素来自html的input name属性。

    function e_($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }
    
    #required fields
    $required = array('name', 'email','lname','message','country' , 'city' ,'adcategory','plan' ,'company');
    $success = false;
    
    #non required fields
    $website = e_($_POST['website']);
    $addr = e_($_POST['address']);
    
    foreach($required as $field) {
        if (empty($_POST[$field]))
        {
            $success = false;
        }
        else if(!empty($_POST[$field])){
            $success = true;
            $name = e_($_POST['fname']);
            $email = e_($_POST['email']); #this has issue
            $lname = e_($_POST['lname']);
            $msg = e_($_POST['message']); #this has issue
    
            $country = e_($_POST['country']);
            $city = e_($_POST['city']);
            $adCategory = e_($_POST['adcategory']);
            $plan = e_($_POST['plan']);
            $companyName = e_($_POST['company']);
        }
    
    }
    
    if($success)        
        echo "success";
    else if (!$success)
        echo json_encode(['errors'=>true]); #this will be manipulated in jquery
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Barmar    6 年前

    问题是你设置了 $success = true; $success = false; 对于上一个字段。你也处理 全部的 else if ,尽管这意味着 找到所需字段的。

    $success = true;
    foreach ($required as $field) {
        if (empty($_POST[$field])) {
            $success = false;
            $missing_field = $field;
            break;
        }
    }
    
    if (!$success) {
        echo json_encode(['errors'=>true, 'missing' => $missing_field]);
        exit();
    }
    
    $name = e_($_POST['fname']);
    $email = e_($_POST['email']); #this has issue
    $lname = e_($_POST['lname']);
    $msg = e_($_POST['message']); #this has issue
    
    $country = e_($_POST['country']);
    $city = e_($_POST['city']);
    $adCategory = e_($_POST['adcategory']);
    $plan = e_($_POST['plan']);
    $companyName = e_($_POST['company']);
    echo "Success";
    
        2
  •  1
  •   Chad K    6 年前

    你的foreach循环是错误的。在for循环中,if语句检查它是否为空。您需要先检查所有值是否为空,然后运行if语句。

    $success = true;
    foreach($required as $field) {
        if (empty($_POST[$field]))
        {
            $success = false;
            break;
        }
    }
    
    if($success)
    {
        // set your variables
    } else {
        // don't set your variables
    }