PHP 表单
- 表单数据被存放在
$_GET
和 $_POST
中 $_SERVER["REQUEST_METHOD]"
返回表单的 method
属性值- htmlspecialchars() 将特殊字符转化为 HTML 表示
示例
登录页面
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>登录</title>
<script>
function validate_form(form) {
with (form) {
if (userName.value == null || userName.value.trim() == "") {
alert("用户名不能为空!");
return false;
}
if (captcha.value == null || captcha.value.trim() == "") {
alert("验证码不能为空!");
return false;
}
}
return true;
}
</script>
</head>
<body>
<form method="post" action="welcome.php" onsubmit="return validate_form(this)">
姓名:<input type="text" name="userName" value=""> <br>
验证码:<input type="text" name="captcha" value="" size=10>
<img title="点击刷新" id="captchaImg" border="1" src="../captcha/captchaImage.php"
onclick="this.src='../captcha/captchaImage.php?r=' + Math.random();"></img><br>
<input type="submit"/>
</form>
</body>
</html>
欢迎页面
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>欢迎</title>
</head>
<body>
<?php
function testInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['captcha'])) {
echo "请输入验证码!";
} else {
$captcha = testInput($_POST['captcha']);
if (strcasecmp($captcha, $_SESSION['captcha']) == 0) {
if (empty($_POST["userName"])) {
echo "用户名不能为空!";
} else {
$userName = testInput($_POST["userName"]);
echo "欢迎," . $userName . "!";
}
} else {
echo "验证码错误!请重新<a href='./form.php'>登录</a>";
}
}
}
?>
</body>
</html>
查看运行结果