PHP语言之表单进阶
第一关
function formatted_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
第二关
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['name'])) {
$nameErr = '名字是必需的';
} else {
$name = formatted_input($_POST['name']);
}
if (empty($_POST['email'])) {
$emailErr = '邮箱是必需的';
} else {
$email = formatted_input($_POST['email']);
}
if (empty($_POST['website'])) {
$website = '';
} else {
$website = formatted_input($_POST['website']);
}
if (empty($_POST['comment'])) {
$comment = '';
} else {
$comment = formatted_input($_POST['comment']);
}
if (empty($_POST['gender'])) {
$genderErr = '性别是必需的';
} else {
$gender = formatted_input($_POST['gender']);
}
}
第三关
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = '只允许字母和空格';
$name = ''; //格式非法,将$name变量清空
}
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
$emailErr = '非法的邮箱格式';
$email = ''; //格式非法,将$email变量清空
}
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = '非法的 URL 地址';
$website = ''; //格式非法,将$website变量清空
}
第四关
$nameErr = $emailErr = $genderErr = $websiteErr = '';
$name = $email = $gender = $comment = $website = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['name'])) {
$nameErr = '名字是必需的';
} else {
$name = formatted_input($_POST['name']);
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = '只允许字母和空格';
$name = ''; //格式非法,将$name变量清空
}
}
if (empty($_POST['email'])) {
$emailErr = '邮箱是必需的';
} else {
$email = formatted_input($_POST['email']);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
$emailErr = '非法的邮箱格式';
$email = ''; //格式非法,将$email变量清空
}
}
if (empty($_POST['website'])) {
$website = '';
} else {
$website = formatted_input($_POST['website']);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = '非法的 URL 地址';
$website = ''; //格式非法,将$website变量清空
}
}
if (empty($_POST['comment'])) {
$comment = '';
} else {
$comment = formatted_input($_POST['comment']);
}
if (empty($_POST['gender'])) {
$genderErr = '性别是必需的';
} else {
$gender = formatted_input($_POST['gender']);
}
}
function formatted_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
来源地址:https://blog.csdn.net/m0_62788719/article/details/127657571