PHP/Form/ POST
Содержание
Basic PHP form processing
<source lang="html4strict">
<?php echo "Hello, " . $_POST["first_name"] . "!"; ?>
</source>
Changing a value in $_POST
<source lang="html4strict">
$_POST["name"] = trim($_POST["name"]); if (strlen($_POST["name"]) == 0) {
$errors[] = "Your name is required.";
}
</source>
if else to check posted variables
<source lang="html4strict">
<?php
$secretNumber = 453; if ($_POST["guess"] == $secretNumber) {echo "
Congratulations!!
";} else {echo "
Sorry!
";}
?>
</source>
Set Cookie Data
<source lang="html4strict">
<?php
$user = $_POST["user"]; $color = $_POST["color"]; $self = $_SERVER["PHP_SELF"]; if( ( $user != null ) and ( $color != null ) ) { setcookie( "firstname", $user , time() + 36000 ); setcookie( "fontcolor", $color, time() + 36000 ); header( "Location:getcookie.php" ); exit(); }
?>
<html>
<head> <title>Set Cookie Data</title> </head> <body> <form action ="<?php echo( $self ); ?>" method = "post"> Please enter your first name: <input type = "text" name = "user">
Please choose your favorite font color:
<input type = "radio" name = "color" value = "#FF0000">Red <input type = "radio" name = "color" value = "#00FF00">Green <input type = "radio" name = "color" value = "#0000FF">Blue
<input type = "submit" value = "submit"> </form> </body>
</html>
</source>
Superglobals vs. Globals
<source lang="html4strict">
<html> <body>
<?php if ($submitted == "yes"){ if (trim ($yourname) != ""){ echo "Your Name: $yourname."; } else { echo "You must submit a value."; } ?>
<a href="index.php">Try Again</a>
<?php } if ($_POST["submitted"] == "yes"){ if (trim ($_POST["yourname"]) != ""){ echo "Your Name: " . $_POST["yourname"] . "."; } else { echo "You must submit a value."; } ?>
<a href="index.php">Try Again</a>
<?php } ?> <?php if ($_POST["submitted"] != "yes"){ ?> <form action="index.php" method="post">
Example:
<input type="hidden" name="submitted" value="yes" /> Your Name: <input type="text" name="yourname" maxlength="150" />
<input type="submit" value="Submit"/> </form> <?php } ?> </div>
</body> </html>
</source>
Testing a required field
<source lang="html4strict">
<?php if (! strlen($_POST["flavor"])) {
print "You must enter your favorite ice cream flavor.";
} ?>
</source>
Verifying a required element
<source lang="html4strict">
if (strlen($_POST["email"]) == 0) {
$errors[] = "You must enter an e-mail address.";
}
</source>