Form Validation - PHP
Form Validation - PHP
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
PHP Forms - Required Fields
p2-formvalidation-2.php if (empty($_POST["comment"])) {
<?php $comment = "";
// define variables and set to empty values } else {
$nameErr = $emailErr = $genderErr = $websiteErr = ""; $comment = test_input($_POST["comment"]);
$name = $email = $gender = $comment = $website = ""; }
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
1. preg_match() is a PHP function used for performing a regular expression match.
2. The regular expression pattern is enclosed within /.../, which checks for the validity of a URL.
3. \b asserts a word boundary, ensuring that the match starts at the beginning of a word.
4. (?:https?|ftp):\/\/ matches either "http://", "https://", or "ftp://".
5. www\. matches "www.".
6. [-a-z0-9+&@#\/%?=~_|!:,.;]*: This matches any combination of characters
commonly found in URLs after the protocol
or "www." part.
7. [-a-z0-9+&@#\/%=~_|]: This matches the last part of the URL.
8. i at the end of the pattern makes the match case-insensitive.