php
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>php表单练习</title>
</head>
<body>
<?php
//php中的htmlspecialchars()可以将用户输入的 "<" ">" 等与html解析有关的特殊字符转换为字符处理
//可以从一定程度上防止XSS
$name = htmlspecialchars($_REQUEST['name']);
$email = htmlspecialchars($_REQUEST['email']);
$hobby = $_REQUEST['hobby'];
$note = htmlspecialchars($_REQUEST['note']);
$gender = htmlspecialchars($_REQUEST['gender']);
if ($_SERVER["REQUEST_METHOD"] == "POST") {//只接收处理POST请求
if (empty($name)){//校验并提示报错信息
$namErr = "姓名不能为空";
}
if (empty($email)){
$emailErr = "邮箱不能为空";
}
if (empty($gender)){
$genderErr = "性别不能为空";
}
}
?>
<!-- 表单 -->
<form action="#" method="post">
名字(*必填):<input type="text" name="name"> <?php echo $namErr; ?><br><!-- 错误提示的输出 -->
邮件(*必填):<input type="text" name="email"> <?php echo $emailErr; ?><br>
爱好:
<input type="checkbox" name="hobby[]" value="绘画">绘画
<input type="checkbox" name="hobby[]" value="音游">音游
<input type="checkbox" name="hobby[]" value="FPS">FPS
<input type="checkbox" name="hobby[]" value="MMORPG">MMORPG
<input type="checkbox" name="hobby[]" value="学习">学习
<br>
性别(*必填):
<input type="radio" name="gender" value="男">男
<input type="radio" name="gender" value="女">女 <?php echo $genderErr; ?><br>
<br>
备注:
<textarea name="note"></textarea><br>
<input type="submit" value="提交">
</form>
<?php
//打印输出提交的表单信息
echo "姓名是:",$name,'<br>';
echo "邮箱是:",$email,'<br>';
echo "爱好是:";
if (!(empty($hobby))){
foreach($hobby as $ah){
echo htmlspecialchars($ah)," ";
}
}
echo '<br>';
echo "性别是:",$gender,'<br>';
echo "备注是:",$note,'<br>';
?>
</body>
</html>