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