PHP 양식 - 이메일 및 URL 확인
이 장에서는 이름, 이메일 및 URL을 확인하는 방법을 보여줍니다.
PHP - 이름 확인
아래 코드는 이름 필드에 문자, 대시, 아포스트로피 및 공백만 포함되어 있는지 확인하는 간단한 방법을 보여줍니다. 이름 필드의 값이 유효하지 않으면 오류 메시지를 저장합니다.
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
preg_match() 함수 는 패턴에 대한 문자열을 검색하여 패턴이 있으면 true를 반환하고 그렇지 않으면 false를 반환합니다.
PHP - 이메일 확인
이메일 주소가 제대로 구성되었는지 확인하는 가장 쉽고 안전한 방법은 PHP의 filter_var() 함수를 사용하는 것입니다.
아래 코드에서 이메일 주소 형식이 올바르지 않으면 오류 메시지를 저장합니다.
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
PHP - URL 확인
아래 코드는 URL 주소 구문이 유효한지 확인하는 방법을 보여줍니다(이 정규식은 URL에 대시도 허용합니다). URL 주소 구문이 유효하지 않은 경우 오류 메시지를 저장합니다.
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
PHP - 이름, 이메일 및 URL 확인
이제 스크립트는 다음과 같습니다.
예시
<?php
// define variables and set to empty values
$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"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>
다음 단계는 사용자가 양식을 제출할 때 양식이 모든 입력 필드를 비우는 것을 방지하는 방법을 보여주는 것입니다.