1、表单处理
<!DOCTYPE HTML>
<html>
<meta Charset="utf-8">
<body>
<form action="get.php" method="get">
姓名:<input type="text" name="name"><br>
电邮:<input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
php文件:
<html>
<body>
Welcome <?php echo $_GET["name"];?><br>
Your email address is:<?php echo $_GET["email"];?><br>
</body>
</html>
2、表单验证:
<!DOCTYPE HTML>
<html>
<head>
<meta Charset="utf-8">
</head>
<body>
<?php
$name = $email = $gender = $comment = $website =" ";
$nameErr = $emainErr = $genderErr = $websiteErr =" ";
if($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "姓名是必填的";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z]*$/",$name)) {
$nameErr = "只允许字母和空格";
}
}
if (empty($_POST["email"])) {
$emailErr = "电邮是必填的";
} else {
$email = test_input($_POST["email"]);
if (!preg_match("/([w-]+@[w-]+.[w-]+)/",$email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["gender"])) {
$genderErr = "性别是必填的";
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["websiteErr"])) {
$websiteErr = "网址是必填的";
} else {
$website = test_input($_POST["website"]);
if (!preg_match("/(?:(?:https?|ftp)://|www.)[-a-z0-9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|]/i",$website)) {
$websiteErr = "无效的 URL";
}
}
$comment = test_input($_POST["comment"]);
}
function test_input($data){
$data = trim($data); //去除空格
$data = stripcslashes($data); //删除反斜杠
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
姓名:<input type="text" name="name">
<span class="error">*<?php echo $nameErr;?></span>
<br>
电邮:<input type="text" name="email">
<span class="error">*<?php echo $emailErr;?></span><br>
网址:<input type="text" name="website">
<span class="error">*<?php echo $websiteErr;?></span>
<br>
评论:<textarea name="comment" rows="5" cols="40"></textarea><br>
性别:<input type="radio" name="gender" value="female">女性
<input type="radio" name="gender" value="male">男性
<span class="error">*<?php echo $genderErr;?></span>
<br>
<input type="submit" name="submit" value="提交">
</form>
<?php
echo "<h2>您的输入</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
echo "<br>";
?>
</body>
</html>