在php中完成表单验证

时间:2016-11-06 21:57:27

标签: php validation

我有这个与数据库相关的PHP代码,我需要在这里做一个完整的电子邮件和名称验证 基于此代码,我该怎么做,因为我的代码在这里有一些问题

1)名称密钥没有(//)或任何符号是正确的名称

2)电子邮件密钥是有效的电子邮件,因为我们在这里做的只是确保有@符号,如果我输入电子邮件hhhh@hhh.com甚至没有(.com)它也会有效吗?!! < / p>

if(array_key_exists("submit",$_POST)){
  $link = mysqli_connect("localhost","root","123456789","users");

  if(mysqli_connect_error()){
    die("There is a problem in connecting to database");
  }

  if(!$_POST['name']){
    $error .="<p>Your Full name is required</p><br>";
  }

  if(!$_POST['email']){
    $error .="<p>Your email address is required</p><br>";
  }

  if(!$_POST['password']){
    $error .="<p>Your password is required</p><br>";
  }

  if($error !=""){
    $error = "<p>There were errors in your form</p><br>".$error;
  }
}

1 个答案:

答案 0 :(得分:0)

您可以使用此功能进行验证:

 function filtervariable($string,$type,$method) {
    //function for sanitizing variables using PHPs built-in filter methods
    $validEmail = false;

    if ($method == 'sanitize') {
        $filtermethod = 'FILTER_SANITIZE_';
    } elseif ($method == 'validate') {
        $filtermethod = 'FILTER_VALIDATE_';
    } else {
        return;
    }
    switch ($type) {
        case 'email':
        case 'string':
        case 'number_int':
        case 'int':
        case 'special_chars':
        case 'url':
        $filtertype = $filtermethod.strtoupper($type);
        break;
    }

    if ($filtertype == 'FILTER_VALIDATE_EMAIL' && !empty($string)) {
        list($local,$domain) = explode('@',$string);

        $localLength = strlen($local);
        $domainLength = strlen($domain);

        $checkLocal = explode('.',$domain);

        if (($localLength > 0 && $localLength < 65) && ($domainLength > 3 && $domainLength < 256) && (checkdnsrr($domain,'MX') || checkdnsrr($domain,'A') || ($checkLocal[1] == 'loc' || $checkLocal[1] == 'dev' || $checkLocal[1] == 'srv'))) { // check for "loc, dev, srv" added to cater for specific problems with local setups
            $validEmail = true;
        } else {
            $validEmail = false;
        }
    }
    if (($filtertype == 'FILTER_VALIDATE_EMAIL' && $validEmail) || $filtertype != 'FILTER_VALIDATE_EMAIL') {
        return filter_var($string, constant($filtertype));
    } else {
        return false;
    }
}

并像这样使用它: $email = filtervariable($registeremail,'email','validate');

它将返回&#34; true&#34;成功和&#34;假&#34;失败。