PHP 시작하기 - 확인 이메일 및 URL
PHP - 이름 확인
다음 코드는 이름 필드에 문자와 공백이 포함되어 있는지 여부를 간단한 방법으로 감지합니다. 값이 합법적이지 않으면 오류 메시지가 출력됩니다
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z) ]*$/ ",$name)) {
$nameErr = "문자와 공백만 허용됩니다.";
}
PHP - 확인 이메일
다음 코드는 이메일 주소가 합법적인지 간단한 방법으로 확인합니다. 이메일 주소가 잘못된 경우 오류 메시지가 출력됩니다:
$email = test_input($_POST["email"]);
if (!preg_match("/([w- ]+@ [w-]+.[w-]+)/",$email)) {
$emailErr = "잘못된 이메일 형식";
}
PHP - URL 확인
다음 코드는 URL 주소가 유효한지 확인합니다(다음 정규 표현식 작업 URL에는 대시: "-"가 포함됨). 불법인 경우 오류가 출력됩니다. 정보:
$website = test_input($_POST["website"]);
if (!preg_match("/b(?:(?:https?| ftp)://|www.)[-a-z0-9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_ |]/i",$website )) {
$websiteErr = "잘못된 URL 주소";
}
PHP - 이름, 이메일, URL 확인
<?php
// 定义变量并默认设置为空值
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// 检测名字是否只包含字母跟空格
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "只允许字母和空格";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} 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"]);
// 检测 URL 地址是否合法
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"]);
}
}
?>


