You can tell the form to submit to the PHP's self, then check the $_POST
variables for form processing. This method is very good for error checking as you can set an error and then have the form reload with any information the user's previously submitted still in tact (i.e. they don't lose their submission).
When the "submit" button is clicked, it will POST the information to the same page, running the PHP code at the top. If an error occurs (based on your checks), the form will reload for the user with the errors displayed and any information the user supplied still in the fields. If an error doesn't occur, you will display a confirmation page instead of the form.
<?php
//Form submitted
if(isset($_POST['submit'])) {
//Error checking
if(!$_POST['yourname']) {
$error['yourname'] = "<p>Please supply your name.</p>
";
}
if(!$_POST['address']) {
$error['address'] = "<p>Please supply your address.</p>
";
}
//No errors, process
if(!is_array($error)) {
//Process your form
//Display confirmation page
echo "<p>Thank you for your submission.</p>
";
//Require or include any page footer you might have
//here as well so the style of your page isn't broken.
//Then exit the script.
exit;
}
}
?>
<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
<?=$error['yourname']?>
<p><label for="yourname">Your Name:</label><input type="text" id="yourname" name="yourname" value="<?=($_POST['yourname'] ? htmlentities($_POST['yourname']) : '')?>" /></p>
<?=$error['address']?>
<p><label for="address">Your Address:</label><input type="text" id="address" name="address" value="<?=($_POST['address'] ? htmlentities($_POST['address']) : '')?>" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…