通过php验证同一页面上的表单


Validate form on same page via php

我试图从用户那里获取信息,经过多次检查后,我想将数据输入数据库。只要表单操作设置为不同的文件(例如:form action = "addnewuser.php"),我在这方面就很成功。但是,我希望在同一页上授权表单,并显示表单本身遇到的任何错误。我知道这是一个多步骤的过程,所以现在我只使用php而不是jquery来显示错误。然而,当我将php文件addnewuser.php的内容复制并粘贴到html表单页面时,它不会显示任何错误。我一直在学习各种网络教程,它们的代码似乎运行得很好。我还无法发现代码中的错误。非常感谢您的帮助。

代码:filename-form.php

<?php
if (($_SERVER['REQUEST_METHOD'] == 'POST') && (!empty($_POST['action']))):
    /*** begin our session ***/
    $firstname = $_REQUEST['firstname'];
    $lastname = $_REQUEST['lastname'];
    $username = $_REQUEST['username'];
    $password = $_REQUEST['password'];
    $password_conf = $_REQUEST['password_conf'];
    $emailid = $_REQUEST['emailid'];
    $team_name = $_REQUEST['team_name'];
//  $secret_answer = $_REQUEST['secret_answer'];
    //$secret_question = $_REQUEST['question'];
/*** first check that both the username, password and form token have been sent ***/
    if(!isset( $username, $password ))
    {
        echo '<div>Please enter a valid username and password</div>';
    }
     /*** check the form token is valid ***/
    // if( $_POST['form_token'] != $_SESSION['form_token'])
    // {
        // echo = 'Invalid form submission';
    // }
     /*** check the username is the correct length ***/
     if (strlen( $username) > 20 || strlen($username) < 4)
     {
         echo 'Incorrect Length for Username';
     }
     if (ctype_alpha($firstname) != true)
     {
             /*** if there is no match ***/
             echo "Username cannot contain numbers";
     }
     if (ctype_alpha($lastname) != true)
     {
             /*** if there is no match ***/
             echo  "Lastname cannot contain numbers";
     }
     /*** check the password is the correct length ***/
     if (strlen( $password) > 20 || strlen($password) < 4)
     {
         echo 'Incorrect Length for Password';
     }
     /*** check the username has only alpha numeric characters ***/
     if (ctype_alnum($username) != true)
     {
         /*** if there is no match ***/
         echo "Username must be alpha numeric";
     }
     /*** check the password has only alpha numeric characters ***/
     if (ctype_alnum($password) != true)
     {
             /*** if there is no match ***/
             echo  "Password must be alpha numeric";
     }
    else
    {
        /*** if we are here the data is valid and we can insert it into database ***/
        // $firstname = filter_var($firstname, FILTER_SANITIZE_STRING);
        // $lastname = filter_var($lastname, FILTER_SANITIZE_STRING);
        $username = filter_var($username, FILTER_SANITIZE_STRING);
        $password = filter_var($password, FILTER_SANITIZE_STRING);
        // $emailid = filter_var($emailid, FILTER_SANITIZE_STRING);
        // $team_name = filter_var($team_name, FILTER_SANITIZE_STRING);

        /*** now we can encrypt the password ***/
        $password = sha1( $password );
        /*** connect to database ***/
        /*** mysql hostname ***/
        $mysql_hostname = 'localhost';
        /*** mysql username ***/
        $mysql_username = 'root';
        /*** mysql password ***/
        $mysql_password = 'hassan28';
        /*** database name ***/
        $mysql_dbname = 'adb project';
        try
        {
            $dbh = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
            /*** echo = a message saying we have connected ***/
            /*** set the error mode to excptions ***/
            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            /*** prepare the insert ***/
            $stmt = $dbh->prepare("INSERT INTO users (firstname,lastname,username, password,emailid,team_name) VALUES ('$firstname', '$lastname',:username, :password,'$emailid', '$team_name')");
            /*** bind the parameters ***/
            $stmt->bindParam(':username', $username, PDO::PARAM_STR);
            $stmt->bindParam(':password', $password, PDO::PARAM_STR, 40);
            /*** execute the prepared statement ***/
            $stmt->execute();

            /*** unset the form token session variable ***/
            /***unset( $_SESSION['form_token'] ); ***/
            /*** if all is done, say thanks ***/
            echo  'New user added';
        }
        catch(Exception $e)
        {
            /*** check if the username already exists ***/
            if( $e->getCode() == 23000)
            {
                echo 'Username already exists';
            }
            else
            {
                /*** if we are here, something has gone wrong with the database ***/
                echo 'We are unable to process your request. Please try again later"';
            }
        }
    }
endif;
?>
<form class="form-inline" method="POST" action="<?php echo $_SERVER['PHP_SELF']?>" >
        <span id="formerror" class="error"></span>
              <p><input type="text" class="span2" maxlength = "20" name="firstname" id="firstname" placeholder="First Name"></p>
              <p><input type="text" class="span2" maxlength = "20" name="lastname"  id="lastame" placeholder="Last Name"></p>
              <p><input type="text" class="span2" maxlength = "20" name="username"  id="username" placeholder="Username"></p>
              <p class="help-block" style="font-size:12px"> Username should be between 4-20 characters long.</p>
              <p><input type="password" class="span2" name="password" placeholder="Password"></p>
              <p class="help-block" style="font-size:12px"> Password must be between 4-20 characters long. Must be alpha-numeric</p>
              <p><input type="password" class="span2" name="password_conf" placeholder="Re - Enter Password"></p>
              <p><input type="email" class="span4" name="emailid"  id="emailid" placeholder="Emaid ID"></p>
              <p><input type="text" class="span2" name="team_name"  id="team_name" placeholder="Team name"></p>
              <p class="help-block" style="font-size:12px"> Select your Unique team name.</p>
              <p>
                  <select class="secret_question">
                     <option value ="city_name">The name of the city where you were born</option>
                     <option value ="first_pet">The name of your first pet</option>
                     <option value ="mother_name">What is your mother's maiden name</option>
                  </select>
                </p>
                <p><input type="text" class="span2" name="secret_answer"  id="secret_answer" placeholder="Secret Answer"></p>
                <p><input type="hidden" value="submit" /><br />
              <button type="submit" name="action" class="btn btn-primary">Register</button></p>
            </form>

在表单中,哪个字段是重新请求的,您只需使用"重新请求"。例如:

<form class="form-inline" method="POST" action="<?php echo $_SERVER['PHP_SELF']?>" >
    <span id="formerror" class="error"></span>
          <p><input type="text" class="span2" maxlength = "20" name="firstname" id="firstname" placeholder="First Name" required></p> 
          <p><input type="text" class="span2" maxlength = "20" name="username"  id="username" placeholder="Username" required></p>
          <p><input type="email" class="span4" name="emailid"  id="emailid" placeholder="Emaid ID" required></p>
          <p><input type="hidden" value="submit" /><br />
          <button type="submit" name="action" class="btn btn-primary">Register</button></p>

为了自己的清晰起见,我对您的代码进行了清理,请随时提出任何问题。

  • 我将消息保存到变量中
  • 我在模板中输出它们

您的代码

class MyQuickException extends Exception {
  public function __construct($code) {
    switch ($code) {
      case 0: $message = 'Please enter a valid username and password'; break;
      case 1: $message = 'Invalid form submission'; break;
      case 2: $message = 'Incorrect Length for Username'; break;
      case 3: $message = 'Username cannot contain numbers'; break;
      case 4: $message = 'Lastname cannot contain numbers'; break;
      case 5: $message = 'Incorrect Length for Password'; break;
      case 6: $message = 'Username must be alpha numeric'; break;
      case 7: $message = 'Password must be alpha numeric'; break;
      default: break;
    }
    parent::__construct($message,$code);
  }
}
if (($_SERVER['REQUEST_METHOD'] === 'POST') && (!empty($_POST['action']))) {
  /*** begin our session ***/
  $firstname = $_REQUEST['firstname'];
  $lastname = $_REQUEST['lastname'];
  $username = $_REQUEST['username'];
  $password = $_REQUEST['password'];
  $password_conf = $_REQUEST['password_conf'];
  $emailid = $_REQUEST['emailid'];
  $team_name = $_REQUEST['team_name'];
  //$secret_answer = $_REQUEST['secret_answer'];
  //$secret_question = $_REQUEST['question'];
  try {
    $error = '';
    if(!isset($username,$password))                       throw new MyException(0);
    if( $_POST['form_token'] != $_SESSION['form_token'])  throw new MyException(1);
    if (strlen( $username) > 20 || strlen($username) < 4) throw new MyException(2);
    if (!ctype_alpha($firstname))                         throw new MyException(3);
    if (!ctype_alpha($lastname))                          throw new MyException(4);
    if (strlen( $password) > 20 || strlen($password) < 4) throw new MyException(5);
    if (!ctype_alnum($username))                          throw new MyException(6);
    if (!ctype_alnum($password))                          throw new MyException(7);
  } catch (Exception $e) {
    $error = $e->getMessage();
  }
  if (!$error) {
    // $firstname = filter_var($firstname, FILTER_SANITIZE_STRING);
    // $lastname = filter_var($lastname, FILTER_SANITIZE_STRING);
    $username = filter_var($username,FILTER_SANITIZE_STRING);
    $password = filter_var($password,FILTER_SANITIZE_STRING);
    // $emailid = filter_var($emailid, FILTER_SANITIZE_STRING);
    // $team_name = filter_var($team_name, FILTER_SANITIZE_STRING);
    $password = sha1($password);
    $mysql_hostname = 'localhost';
    $mysql_username = 'root';
    $mysql_password = 'hassan28';
    $mysql_dbname = 'adb project';
    try {
      $dbh = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
      $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $stmt = $dbh->prepare("INSERT INTO users (firstname,lastname,username, password,emailid,team_name) VALUES ('$firstname', '$lastname',:username, :password,'$emailid', '$team_name')");
      $stmt->bindParam(':username',$username,PDO::PARAM_STR);
      $stmt->bindParam(':password',$password,PDO::PARAM_STR, 40);
      $stmt->execute();
      //unset($_SESSION['form_token']);
      $msg = 'New user added';
    } catch(Exception $e) {
      $msg = $e->getCode() == 23000 ? 'Username already exists' : 'We are unable to process your request. Please try again later"';
    }
  }
}
?>
<!-- messages will be output here, change to fit your needs -->
<p><?php echo $error ? $error : $msg; ?></p>
<form class="form-inline" method="POST" action="<?php echo $_SERVER['PHP_SELF']?>" >
  <span id="formerror" class="error"></span>
  <p><input type="text" class="span2" maxlength="20" name="firstname" id="firstname" placeholder="First Name"></p>
  <p><input type="text" class="span2" maxlength="20" name="lastname"  id="lastame" placeholder="Last Name"></p>
  <p><input type="text" class="span2" maxlength="20" name="username"  id="username" placeholder="Username"></p>
  <p class="help-block" style="font-size:12px"> Username should be between 4-20 characters long.</p>
  <p><input type="password" class="span2" name="password" placeholder="Password"></p>
  <p class="help-block" style="font-size:12px"> Password must be between 4-20 characters long. Must be alpha-numeric</p>
  <p><input type="password" class="span2" name="password_conf" placeholder="Re - Enter Password"></p>
  <p><input type="email" class="span4" name="emailid"  id="emailid" placeholder="Emaid ID"></p>
  <p><input type="text" class="span2" name="team_name"  id="team_name" placeholder="Team name"></p>
  <p class="help-block" style="font-size:12px"> Select your Unique team name.</p>
  <p>
    <select class="secret_question">
       <option value ="city_name">The name of the city where you were born</option>
       <option value ="first_pet">The name of your first pet</option>
       <option value ="mother_name">What is your mother's maiden name</option>
    </select>
  </p>
  <p><input type="text" class="span2" name="secret_answer"  id="secret_answer" placeholder="Secret Answer"></p>
  <p><input type="hidden" value="submit" /></p>
  <button type="submit" name="action" class="btn btn-primary">Register</button></p>
</form>

如果不起作用,请给出反馈,不要忘记将某人的答案标记为答案