使用php验证html页面上的字段 [英] Validate fields on html page with php

查看:101
本文介绍了使用php验证html页面上的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查找index.html和submit.php文件的代码。在 loopo 的帮助下,两者都非常完美。我正在苦苦挣扎地放置验证码(在index.html文件或submit.php文件中)。我在html文件中使用html5输入类型,我不知道确认在submit.php文件中的确切位置。我有多种形式,我按照建议制作了validations.php。我也不明白错误信息的显示位置在哪里?

Please find code of index.html and submit.php file. With the help of loopo, both are working perfect. I am struggling where excatly to put the validation code (in index.html file or submit.php file). i am using html5 input types in html file and I dont know where exactly the validation has to happen in submit.php file. I have multiple forms and I made validations.php as suggested. I am also not understanding where will the error messages been shown?

你能否在submit.php文件中建议一个位置,我应该通过编辑我的submit.php文件来添加这些验证?

电子邮件的正则表达式('/ ^ [_ a-z0-9 - ] +(\。[_ a-z0-9 - ] +)* @ [a-z0- 9 - ] +(\。[a-z0-9 - ] +)*(\。[az] {2,3})$ /'
Regexp for phone( ^(:( ?: \ + | 0 {0,2})91(\s * [\-] \s *)|???[0])[789 ] \d {9} $

Can you suggest a location in the submit.php file where I should add these validations by editing my submit.php file?
Regexp for email ('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/')
Regexp for phone (^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$)

index.html文件

<form method="post" action="submit.php">
    <div class="box">
        <div class="cl"><input type="text" name="name" placeholder="Name" /></div>
        <div class="cl"><input type="text" name="city" placeholder="City" /></div>
        <div class="cl"><input type="text" name="mobile" placeholder="Mobile" /></div>
        <div class="cl"><input type="email" name="email" placeholder="Email" /></div>
        <div class="cl"><input type="text" name="sub" placeholder="Want 3 m Free Subscription (Yes/No)?"></textarea></div>
        <div class="cl"><input type="text" name="slogan" placeholder="Suggest a slogan for 6 m subscription"></textarea></div>
    </div>
    <div class="srow">
        <div class="cl1">
            <ul class="action">
                <li><input type="submit" value="Submit" /></li>
            </ul>
        </div>
    </div>
</form>

submit.php文件

<?php
include 'config.php'; // store your configuration in a seperate file so 
                      // you only need to update it once when your environment changes

$errors = false;
$output = '';
$nl = '<br>'.PHP_EOL;
$redirect_url = 'index.html';

if (!$con = new mysqli(DBHOST,DBUSER,DBPASS,DBNAME)){
    $errors = true;
    $output .= "ERROR Can't connect to DB".$nl;
};   


if (!$errors){
   //should validate/clean $_POST before using in query
   $name = $con->escape_string($_POST['name']);
   $city = $con->escape_string($_POST['city']);
   $email = $con->escape_string($_POST['email']);
   $mobile = $con->escape_string($_POST['mobile']);
   $sub = $con->escape_string($_POST['sub']);
   $slogan = $con->escape_string($_POST['slogan']);

   $sql="INSERT INTO members 
            (sName, sCity, sMobile, sEmail, sSub, sSlogan)
         VALUES ('$name', '$city', '$mobile', '$email',
                '$sub','$slogan')";

   if (!$con->query($sql)){ //forgot a parenthesis here earlier
      $output .= 'ERROR: DB said: ('.$con->errno.') '.$con->error.$nl;
      $output .= 'Query was:'.$sql.$nl;
      $errors = true;
   }else{
     $output .= "1 record added".$nl;
   }
}

if (!$errors){
   //if there are no errors redirect to index.html;
   header('refresh: 2; URL='.$redirect_url);
   $output .= '...Redirecting...'.$nl;
}else{
   //show the errors and allow display a link to go back/try again
   $output .= '<a href="'.$redirect_url.'">Try again</a>'.$nl;
}
echo $output;
?>

loopo 但不知道确切的位置。我制作了一个validations.php文件并包含在submit.php中,但可能是我的语法错误,因为它无效。

Validations suggested by loopo but dont know exact location to put it. I made a validations.php file and included in submit.php but may be my syntax is wrong because of which it is not working.

function validate_name($input){
    // fairly naive rule:
    // upper and lower case latin characters and space
    // at least three character long
    // you may want to look at allowing other characters such as é ö etc.
    $input = trim($input); //get rid of spaces at either end
    if (preg_match('/^[a-zA-Z ]{3,}$/',$input) == 1){
        return $input;
    }else{
        return false;
    }
}

  if (!empty($_POST['name']){
    if (!$name = $con->escape_string(validate_name($_POST['name'])){
        $error = true;
        $output .= 'ERROR: Invalid Name: '.$_POST['name'].$nl;
    }
  }else{
    $error = true;
    $output .= 'ERROR: No name specified'.$nl;
  }


推荐答案

通过直接向php文件发送请求可以绕过html验证,因此验证信息服务器端是你做的一个不错的选择。

html validations can be bypassed by sending a request directly to the php file, so validating info on server-side is a good choice you made.

我建议你最好使用php的内置函数 filter_var ,为了获得干净的代码和准确/安全的结果,请尝试以下方法:

i suggest you better use php's built-in function filter_var, for clean code and accurate/safe results, try this:

function validateEmail($email){
    if(filter_var($email,FILTER_VALIDATE_EMAIL)){
        return true;
    }
}

function validatePhonenb($nb){
    if(filter_var($nb,FILTER_VALIDATE_REGEXP,array("options"=>array("regexp"=>"/^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$/"))){
        return true;
    }
}

由于没有验证电话号码,我使用你的正则表达式,顺便说一句你可以使用var_filter 清理电话号码而不是验证它

and since there is no validating for phone numbers, i used your regex, btw you can sanitizethe phone number using var_filter before proceeding instead of validating it


我有多个表格,我按照建议制作了validations.php。我是
也不了解错误消息的显示位置

I have multiple forms and I made validations.php as suggested. I am also not understanding where will the error messages been shown

错误消息将显示在页面底部因为它们在代码的末尾被回显

error messages will be shown in the bottom of the page since they are being echoed in the end of the code

echo $output;
?>

如果他们没有被取代,则改变回显包含错误的输出的位置并执行 die()之后脚本将在显示错误后停止执行

if they are not being displaced change the position of echoing the output containing errors and execute die() after it so the script will stop execution after it showed the errors

这篇关于使用php验证html页面上的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆