In this section we will introduce how to verify names, e-mails, and URLs.
The following code will use a simple way to detect whether the name field contains letters and spaces. If the name field value is illegal, an error message will be output:
$name = test_input($_POST["name"]);if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "Only letters and spaces allowed"; }
preg_match — perform regular expression matching. grammar: int preg_match ( string $pattern , string $subject [, array $matches [, int $flags ]] ) Searches the subject string for a match to the regular expression given by pattern. If matches is provided, it will be populated with the results of the search. $matches[0] will contain text that matches the entire pattern, $matches[1] will contain text that matches the first captured subpattern in parentheses, and so on. |
The following code will check whether the e-mail address is legitimate in a simple way. If the e-mail address is illegal, an error message will be output:
$email = test_input($_POST["email"]);if (!preg_match("/([w-]+@[w-]+.[w-]+)/" ,$email)) { $emailErr = "Illegal email format"; }
The following code will check whether the URL address is legal (the following regular expression runs in the URL containing dashes: "-"). If the URL address is illegal, an error message will be output:
$website = test_input($_POST["website"]);if (!preg_match("/b(?:(?:https?|ftp)://|www.)[-a-z0- 9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|]/i",$website)) { $websiteErr = "Illegal URL address"; }
The code looks like this:
<?php// Define variables and set them to empty values by default $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 whether the name only contains letters and spaces if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "Only letters and spaces allowed"; } } if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = test_input($_POST["email"]); // Check whether the email is legal if (!preg_match("/([w-]+@[w-]+.[w-]+ )/",$email)) { $emailErr = "Illegal email format"; } } if (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); // Check whether the URL address is legal if (!preg_match("/b(?:(?:https?|ftp)://|www.)[- a-z0-9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|]/i",$website) ) { $websiteErr = "Illegal URL address"; } } 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"]); }}?>