菜鳥教程PHP學習筆記(不定期更新)
阿新 • • 發佈:2018-11-30
NO.1—PHP表單驗證
程式碼詳細註釋版
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>菜鳥教程(runoob.com)</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$nameErr=$emailErr=$genderErr=$websiteErr="";
$name=$email=$comment =$website="";
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 = "非法郵箱格式";
}
}
if(empty($_POST["website"]))
{
$website="";
}
else
{
$website=test_input($_POST ["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website))
{
$websiteErr = "非法的 URL 的地址";
}
}
if (empty($_POST["comment"]))
{
$comment = "";
}
else
{
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"]))
{
$genderErr = "性別是必需的";
}
else
{
$gender = test_input($_POST["gender"]);
}
}
function test_input($data)
{
$data=trim($data);//去除不必要的字元如空格換行
$data=stripslashes($data);//去除反斜槓
$data=htmlspecialchars($data);//將資料進行處理防止被黑客利用
}
?>
<h2>php表單驗證例項</h2>
<p><span class="error">*必需欄位</span></p>
<form method="post" action="<?php echo ?>">