简体   繁体   中英

how can I get the action attribute in form tag to work correctly?

I know the tag form has an attribute called action and I know how action works, this is how I used it

<form method="post" action = "registerd.php">
</form>

The registerd.php page also exists as well. Now I am doing some validation in the tag form using php validation, but why does it jump to the registerd.php page without validating the values at first? is there any other solutions to this rather than using the header at the end of php code like :

header("location : registerd.php")

here is the whole code I'm writing Thank you very much in advance

<div id = "content">
            <?php
                $fnameErr = "";
                $lnameErr = "";
                $idErr = "";
                $placeErr = "";
                $dateErr = "";
                $emailErr = "";
                $pswErr = "";
                $file;
                $content = "";
                function test_input($data) {
                    $data = trim($data);
                    $data = stripslashes($data);
                    $data = htmlspecialchars($data);
                    return $data;
                }
                if(isset($_POST['register'])){
                    if(isset($_POST['firstname'])){
                        if(!empty($_POST['firstname'])){
                            if(strlen($_POST['firstname'])>1){
                                if(preg_match("/[a-zA-Z]+/", $_POST['firstname'])==1){
                                    $firstname = test_input($_POST['firstname']);
                                    $content .= "firstname:";
                                    $content .= $firstname; 
                                    $content .= " ";
                                }
                                else{   
                                    $fnameErr = "your first name should only include letters";
                                }
                            }
                            else{
                                $fnameErr = "your first name must be at least 2 characters";
                            }
                        }
                        else{
                            $fnameErr = "enter your first name";
                        }
                    }
                    else{
                        $fnameErr = "enter your first name";
                    }
                    if(isset($_POST['lastname'])){
                        if(!empty($_POST['lastname'])){
                            if(strlen($_POST['lastname'])>3){
                                if(preg_match("/[a-zA-Z]+/", $_POST['lastname'])==1){
                                    $lastname = test_input($_POST['lastname']);
                                    $content .= "lastname:";
                                    $content .= $lastname;
                                    $content .= " ";
                                }
                                else{
                                    $lnameErr = "your last name should only include letters";
                                }
                            }
                            else{
                                $lnameErr = "your last name must be at least 2 characters";
                            }
                        }
                        else{
                            $lnameErr = "enter your last name";
                        }
                    }
                    else{
                        $lnameErr = "enter your last name";
                    }

                    if(isset($_POST['idnum'])){
                        if(!empty($_POST['idnum'])){
                            if(strlen($_POST['idnum'])==10){
                                if(preg_match("/[0-9]{10}/", $_POST['idnum'])==1){
                                    $idnum = test_input($_POST['idnum']);
                                    $content .= "ID_No.:";
                                    $content .= $idnum;
                                    $content .= " ";
                                }
                                else{
                                    $idErr = "your ID number should only include digits";
                                }
                            }
                            else{
                                $idErr = "your ID number must be 10 digits";
                            }
                        }
                        else{
                            $idErr = "enter your ID number";
                        }
                    }
                    else{
                        $idErr = "enter your ID number";
                    }
                    if(isset($_POST['placeOfBirth'])){
                        if(!empty($_POST['placeOfBirth'])){
                            if(strlen($_POST['placeOfBirth'])>2){
                                if(preg_match("/[a-zA-Z]+/", $_POST['placeOfBirth'])==1){
                                    $placeOfBirth = test_input($_POST['placeOfBirth']);
                                    $content .= "placeOfBirth:";
                                    $content .= $placeOfBirth;
                                    $content .= " ";
                                }
                                else{
                                    $placeErr = "your place of birth should only include digits";
                                }
                            }
                            else{
                                $placeErr = "your place of birth must be at least 3 letters";
                            }
                        }
                    }   
                    if(isset($_POST['date'])){
                        if(!empty($_POST['date'])){
                            $date = test_input($_POST['date']);
                            $content .= "date:";
                            $content .= $date;
                            $content .= " ";
                        }
                        else{
                            $dateErr = "enter your date of birth";
                        }
                    }
                    else{
                        $dateErr = "enter your date of birth";
                    }


                    if(isset($_POST['email'])){
                        if(!empty($_POST['email'])){
                                $email = test_input($_POST['email']);
                                $content .= "email:";
                                $content .= $email;
                                $content .= " ";
                        }
                        else{
                            $emailErr = "enter your email";
                        }
                    }
                    else{
                        $emailErr = "enter your email";
                    }

                    if(isset($_POST['password'])){
                        if(!empty($_POST['password'])){
                                if(preg_match("/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$/", $_POST['password'])==1){
                                    $password = test_input($_POST['password']);
                                    $content .= "password:";
                                    $content .= $password;
                                    $content .= " ";
                                }
                                else{
                                    $pswErr = "your password should have numbers, uppercase<br/> & lowercase letters";
                                }
                        }
                        else{
                            $pswErr = "enter your password";
                        }
                    }
                    else{
                        $pswErr = "enter your password";
                    }
                    if(file_exists($email.".txt")){
                        echo(
                            "<script>
                                alert('this email already exists!');
                            </script>"
                            );
                        $firstname = $lastname = $idnum = $date = $placeOfBirth = $password = "";
                    }
                    else{
                        $file = fopen($email.".txt","a+") or die("Unable to open file!");
                        fwrite($file, $content);
                        fclose($file);
                        header("location: registered.php");
                    }
                }
            ?>
            <fieldset id = "fieldset">
                <legend><h1 class = "reg" >Register Form</h1></legend>
                <form method="post" action="#" enctype = "multipart/form-data">
                <table class = "table">
                    <tr>
                        <td  class = "labels">
                            <p class = "star">*</p> First Name
                        </td>
                        <td><input class = "inclass" type="text" required="required" placeholder="Please enter your first name" id = "firstname" name="firstname" onclick = "colorBorder(this.id)"/></td>
                    </tr>
                    <td  class = "err">
                        <span>
                                <?php
                                    echo $fnameErr;
                                ?>
                        </span>
                    </td>
                    <tr>
                        <td class = "labels"><p class = "star">*</p> Last Name</td>
                        <td><input class = "inclass" type="text" required="required" placeholder="Please enter your last name" name="lastname" id = "lastname" onclick = "colorBorder(this.id)"/></td>
                    </tr>
                    <td  class = "err">
                        <span>
                                <?php
                                    echo $lnameErr;
                                ?>
                        </span>
                    </td>
                    <tr>
                        <td class = "labels">Gender</td>
                        <td>
                            <input class = "inclass" type="radio" name="gender" value="0" /><p class = "radio" >Male</p>
                            <input class = "inclass" type="radio" name="gender" value="1" /><p class = "radio" >Female</p>
                        </td>
                    </tr>
                    <tr>
                        <td class = "labels"><p class = "star">*</p> ID Number</td>
                        <td><input class = "inclass" type="text" id="idnum" required="required" placeholder="Please enter your ID number" name="idnum" onclick = "colorBorder(this.id)"/></td>
                    </tr>
                    <td  class = "err">
                        <span>
                                <?php
                                    echo $idErr;
                                ?>
                        </span>
                    </td>
                    <tr>
                        <td class = "labels">Place of Birth</td>
                        <td><input class = "inclass" type="text" placeholder="Please enter your place of birth" name="placeOfBirth" id = "place" onclick = "colorBorder(this.id)"/></td>
                    </tr>
                    <td  class = "err">
                        <span>
                                <?php
                                    echo $placeErr;
                                ?>
                        </span>
                    </td>
                    <tr>
                        <td class = "labels"><p class = "star">*</p> Date Of Birth</td>
                        <td><input class = "inclass" type="date" id = "date" name="date"/></td>
                    </tr>
                    <td  class = "err">
                        <span>
                                <?php
                                    echo $dateErr;
                                ?>
                        </span>
                    </td>
                    <tr>
                        <td class = "labels"><p class = "star">*</p> Email</td>
                        <td><input class = "inclass" type="email" required="required" placeholder="Please enter your email" name="email" id = "email" onclick = "colorBorder(this.id)"/></td>
                    </tr>
                    <td  class = "err">
                        <span>
                                <?php
                                    echo $emailErr;
                                ?>
                        </span>
                    </td>
                    <tr>
                        <td class = "labels"><p class = "star">*</p> Passwords</td>
                        <td><input class = "inclass" type="password" required="required" placeholder="Please enter your password" name="password" id = "password" onclick = "colorBorder(this.id)"/></td>
                    </tr>
                    <td  class = "err">
                        <span>
                                <?php
                                    echo $pswErr;
                                ?>
                        </span>
                    </td>
                    <tr>
                        <td><input type="submit" name="register" value="register" class="save"/></td>
                        <td><input type="reset" name = "reset" id = "reset"/></td>
                    </tr>
                </table>
                </form>
            </fieldset>
        </div>

在register.php上写下您的php验证代码,如果值没有得到验证,则使用标头函数重定向到您的表单页面。

header("location : form.php")

The approach adopted below bypasses the superfluous use of isset . This also means that the checking for all $_POST['data'] Variables where consolidated unto one section of the Code, right after checking if the Submit Button-Value was set. The Function function test_input($data) {...} was completely removed since the Section mentioned above also does exactly the same thing... Multiline String-Concatenation was condensed to one single Line for brevity... There seemed also to be some extraneous if(){...}else{...} clauses all over the place. Those were ignored since they might serve some purpose to the Original Poster (though unlikely). Finally, to ensure that the form is posted back to the Current, Executing Script (considering that the processing of the Form Data is in the same Script); we would leave the action Attribute of the Form EMPTY: meaning that the Form would automatically post back to itself - the current Script.

    <?php
        // AT THE VERY TOP OF THE SCRIPT - PREFERABLY NOT WITHIN A DIV OR ANY CONTAINER, START YOUR PHP CODES...
        $fnameErr   = "";
        $lnameErr   = "";
        $idErr      = "";
        $placeErr   = "";
        $dateErr    = "";
        $emailErr   = "";
        $pswErr     = "";
        $content    = "";
        $file;


        if(isset($_POST['register'])){
            // GATHER A FILTERED VERSION OF THE POST VARIABLES:
            $firstName      = isset($_POST['firstname'])    ? htmlspecialchars(stripslashes(trim($_POST['firstname'])))     : null;
            $lastName       = isset($_POST['lastname'])     ? htmlspecialchars(stripslashes(trim($_POST['lastname'])))      : null;
            $idNum          = isset($_POST['idnum'])        ? htmlspecialchars(stripslashes(trim($_POST['idnum'])))         : null;
            $placeOfBirth   = isset($_POST['placeOfBirth']) ? htmlspecialchars(stripslashes(trim($_POST['placeOfBirth'])))  : null;
            $date           = isset($_POST['date'])         ? htmlspecialchars(stripslashes(trim($_POST['date'])))          : null;
            $email          = isset($_POST['email'])        ? htmlspecialchars(stripslashes(trim($_POST['email'])))         : null;
            $password       = isset($_POST['password'])     ? htmlspecialchars(stripslashes(trim($_POST['password'])))      : null;


            if($firstName){
                if(!empty($firstName)){
                    if(strlen($firstName)>1){
                        if(preg_match("/[a-zA-Z]+/", $firstName)==1){
                            $content .= "firstname:" . $firstName . " ";
                        }
                        else{
                            $fnameErr = "Your first name should only include letters";
                        }
                    }
                    else{
                        $fnameErr = "Your first name must be at least 2 characters";
                    }
                }
                else{
                    $fnameErr = "Enter your first name";
                }
            }else{
                $fnameErr = "Enter your first name";
            }

            if(isset($lastName)){
                if(!empty($lastName)){
                    if(strlen($lastName)>3){
                        if(preg_match("/[a-zA-Z]+/", $_POST['lastname'])==1){
                            $content .= "lastname:" . $lastName . " ";
                        }
                        else{
                            $lnameErr = "Your last name should only include letters";
                        }
                    }
                    else{
                        $lnameErr = "Your last name must be at least 2 characters";
                    }
                }
                else{
                    $lnameErr = "Enter your last name";
                }
            }else{
                $lnameErr = "Enter your last name";
            }

            if(isset($idNum)){
                if(!empty($idNum)){
                    if(strlen($idNum) == 10){
                        if(preg_match("/[0-9]{10}/", $_POST['idnum'])==1){
                            $content .= "ID_No.:" .  $idNum . " ";
                        }
                        else{
                            $idErr = "Your ID number should only include digits";
                        }
                    }
                    else{
                        $idErr = "Your ID number must be 10 digits";
                    }
                }
                else{
                    $idErr = "Enter your ID number";
                }
            }else{
                $idErr = "Enter your ID number";
            }

            if(isset($placeOfBirth)){
                if(!empty($placeOfBirth)){
                    if(strlen($placeOfBirth)>2){
                        if(preg_match("/[a-zA-Z]+/", $placeOfBirth)==1){
                            $content .= "placeOfBirth:" . $placeOfBirth . " ";
                        }
                        else{
                            $placeErr = "Your place of birth should only include digits";
                        }
                    }else{
                        $placeErr = "Your place of birth must be at least 3 letters";
                    }
                }
            }

            if(isset($date)){
                if(!empty($date)){
                    $content .= "date:" . $date . " ";
                }else{
                    $dateErr = "Enter your date of birth";
                }
            }else{
                $dateErr = "Enter your date of birth";
            }

            if(isset($email)){
                if(!empty($email)){
                    $content .= "email:" .  $email . " ";
                }else{
                    $emailErr = "Enter your email";
                }
            }else{
                $emailErr = "Enter your email";
            }

            if(isset($password)){
                if(!empty($password)){
                    if(preg_match("/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$/", $password)==1){
                        $content .= "password:" .  $password . " ";
                    }else{
                        $pswErr = "Your password should have numbers, uppercase<br/> & lowercase letters";
                    }
                }else{
                    $pswErr = "Enter your password";
                }
            }else{
                $pswErr = "Enter your password";
            }

            if(file_exists($email.".txt")){
                echo "<script type='text/javascript'>alert('this email already exists!');</script>";            
                $firstname = $lastname = $idnum = $date = $placeOfBirth = $password = "";
            }
            else{
                $file = fopen($email.".txt","a+") or die("Unable to open file!");
                fwrite($file, $content);
                fclose($file);
                header("location: registered.php");
            }
        }
    ?>

    <div id = "content">
        <fieldset id = "fieldset">
            <legend><h1 class = "reg" >Register Form</h1></legend>
            <!-- SINCE YOUR VALIDATION IS IN THE CURRENT SCRIPT, LEAVING THE  action ATTRIBUTE EMPTY IMPLIES THAT THE FORM WILL POST BACK TO ITSELF [THE CURRENT SCRIPT]. -->
            <form method="POST" action="" enctype = "multipart/form-data">
                <table class = "table">

                    <tr>
                        <td  class = "labels">
                            <p class = "star">*</p> First Name
                        </td>
                        <td>
                            <input class = "inclass" type="text" required="required" placeholder="Please enter your first name" id = "firstname" name="firstname" onclick = "colorBorder(this.id)"/>
                        </td>
                        <td  class = "err">
                            <span><?php echo $fnameErr; ?></span>
                        </td>
                    </tr>

                    <tr>
                        <td class = "labels"><p class = "star">*</p> Last Name</td>
                        <td>
                            <input class = "inclass" type="text" required="required" placeholder="Please enter your last name" name="lastname" id = "lastname" onclick = "colorBorder(this.id)"/>
                        </td>
                        <td  class = "err">
                            <span><?php echo $lnameErr; ?></span>
                        </td>
                    </tr>

                    <tr>
                        <td class = "labels">Gender</td>
                        <td>
                            <input class = "inclass" type="radio" name="gender" value="0" /><p class = "radio" >Male</p>
                            <input class = "inclass" type="radio" name="gender" value="1" /><p class = "radio" >Female</p>
                        </td>
                    </tr>

                    <tr>
                        <td class = "labels"><p class = "star">*</p> ID Number</td>
                        <td>
                            <input class = "inclass" type="text" id="idnum" required="required" placeholder="Please enter your ID number" name="idnum" onclick = "colorBorder(this.id)"/>
                        </td>
                        <td  class = "err">
                            <span><?php echo $idErr; ?></span>
                        </td>
                    </tr>

                    <tr>
                        <td class = "labels">Place of Birth</td>
                        <td>
                            <input class = "inclass" type="text" placeholder="Please enter your place of birth" name="placeOfBirth" id = "place" onclick = "colorBorder(this.id)"/>
                        </td>
                        <td  class = "err">
                            <span><?php echo $placeErr; ?></span>
                        </td>
                    </tr>

                    <tr>
                        <td class = "labels"><p class = "star">*</p> Date Of Birth</td>
                        <td>
                            <input class = "inclass" type="date" id = "date" name="date"/>
                        </td>                   
                        <td  class = "err">
                            <span><?php echo $dateErr; ?></span>
                        </td>
                    </tr>

                    <tr>
                        <td class = "labels"><p class = "star">*</p> Email</td>
                        <td>
                            <input class = "inclass" type="email" required="required" placeholder="Please enter your email" name="email" id = "email" onclick = "colorBorder(this.id)"/>
                        </td>
                        <td  class = "err">
                            <span><?php echo $emailErr; ?></span>
                        </td>
                    </tr>

                    <tr>
                        <td class = "labels"><p class = "star">*</p> Passwords</td>
                        <td>
                            <input class = "inclass" type="password" required="required" placeholder="Please enter your password" name="password" id = "password" onclick = "colorBorder(this.id)"/>
                        </td>
                        <td  class = "err">
                            <span><?php echo $pswErr; ?></span>
                        </td>
                    </tr>

                    <tr>
                        <td>&nbsp;</td>
                        <td><input type="submit" name="register" value="register" class="save"/></td>
                        <td><input type="reset" name = "reset" id = "reset"/></td>
                    </tr>

                </table>
            </form>
        </fieldset>
    </div>

I believe the solution to your problem is to separate your code, the HTML in one file ("form.php"), the PHP validation in another file ("validate.php") :

  • "form.php" will collect the data, the "action" of the form will execute "validate.php".
  • "validate.php" will validate the data, if no error found it will "header" to "registered.php", if error found it will store the message in $_SESSION and "header" back to "form.php", where the message will be displayed.

Example :

form.php

<?php
session_start(); // NECESSARY TO USE $_SESSION.
?>
<html>
  <body>
    <form action="validate.php" method="post">
      Enter 0 or 1 : <input type="text" name="num"/>
      <br/>
      <input type="submit" value="Submit"/>
    </form>
<?php
// CHECK IF THERE IS ERROR MESSAGE FROM VALIDATION.
if ( isset( $_SESSION[ "err_msg" ] ) )
   { echo $_SESSION[ "err_msg" ];
     unset( $_SESSION[ "err_msg" ] ); // VERY IMPORTANT : DESTROY ERROR MESSAGE.
   }
?>
  </body>
</html>

validate.php

<?php
session_start(); // NECESSARY TO USE $_SESSION.
if ( isset( $_POST[ "num" ] ) ) // IF CALLED FROM "FORM.PHP"
     { $num = $_POST[ "num" ];
       if ( ( $num == "0" ) || ( $num == "1" ) ) // VALIDATE NUMBER.
            header( "Location: registered.php" ); // NO ERROR.
       else { $_SESSION[ "err_msg" ] = "Number must be 0 or 1."; // MESSAGE.
              header( "Location: form.php" ); // ERROR.
            }
     }
else header( "Location: form.php" ); // WASN'T CALLED FROM "FORM.PHP".
?>

Create two files with the given names and copy-paste previous codes, then run "form.php".

You will have to paste all your huge validation in "validate.php". Your validation has many messages, I recommend you to insert one "header" after each message and add "exit" immediately after (because "header" does not stop the execution of the script).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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