PHP Form URL/E-mail
PHP Forms - Validate Email and URL
Section titled “PHP Forms - Validate Email and URL”This chapter focuses on validating common form inputs like names, email addresses, and URLs using modern PHP practices.
Input Sanitization and Validation
Section titled “Input Sanitization and Validation”Before validating, it’s crucial to sanitize input data retrieved from $_POST or $_GET. A common helper function might look like this:
<?php// Basic input sanitization functionfunction sanitize_input(string $data): string { $data = trim($data); // Remove leading/trailing whitespace $data = stripslashes($data); // Remove backslashes added by magic quotes (legacy) $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8'); // Convert special characters to HTML entities to prevent XSS return $data;}?>htmlspecialchars() is vital for security to prevent Cross-Site Scripting (XSS) attacks when displaying user-provided data back in HTML.
PHP - Validate Name
Section titled “PHP - Validate Name”Validating names can be complex due to variations across cultures. A simple approach might check for letters and whitespace, but this is often too restrictive.
Simple example (allows only letters and whitespace):
<?php$name = sanitize_input($_POST["name"] ?? ''); // Use null coalescing operator for safety$nameErr = "";
if (!empty($name)) { // Basic check: allows letters (Unicode) and spaces if (!preg_match("/^[pLs'-]+$/u", $name)) { $nameErr = "Only letters, spaces, hyphens, and apostrophes allowed"; }} else { $nameErr = "Name is required";}
// The pattern used:// ^ asserts position at start of the string// [pLs'-]+ matches one or more Unicode letters (pL), whitespace (s), hyphens, or apostrophes// $ asserts position at the end of the string// u modifier enables Unicode matching?>Note: The preg_match() function searches a string for a pattern (regular expression). The pattern /^[pLs'-]+$/u is more inclusive than /^[a-zA-Z ]*$/, allowing Unicode letters, spaces, hyphens, and apostrophes. Adjust the pattern based on your specific requirements.
PHP - Validate Email
Section titled “PHP - Validate Email”The recommended way to validate email addresses in PHP is using the filter_var() function with the FILTER_VALIDATE_EMAIL filter. It checks if the format looks like a valid email address.
<?php$email = sanitize_input($_POST["email"] ?? '');$emailErr = "";
if (!empty($email)) { if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; }} else { $emailErr = "Email is required";}?>Important: FILTER_VALIDATE_EMAIL checks the syntax only. It doesn’t verify if the email address actually exists.
PHP - Validate URL
Section titled “PHP - Validate URL”Similarly, filter_var() with FILTER_VALIDATE_URL is the preferred method for validating URLs.
<?php$website = sanitize_input($_POST["website"] ?? '');$websiteErr = "";
// URL is often optional, so only validate if providedif (!empty($website)) { // FILTER_VALIDATE_URL requires a scheme (like http:// or https://) // To allow URLs like www.example.com, you might need additional logic or regex if (!filter_var($website, FILTER_VALIDATE_URL)) { $websiteErr = "Invalid URL format (e.g., must include http:// or https://)"; }}// No error if website is empty, assuming it's optional.?>Note: FILTER_VALIDATE_URL is quite strict and usually requires a scheme (like http://). If you need to validate less strict URLs (e.g., www.example.com), you might need to combine it with checks or use a more complex regular expression, though filter_var is generally safer.
PHP - Combined Validation Example
Section titled “PHP - Combined Validation Example”Here’s how the validation logic might look integrated into a typical form processing script:
<?phpdeclare(strict_types=1);
// Basic input sanitization function (define once)function sanitize_input(string $data): string { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8'); return $data;}
// Define variables and initialize with empty values$nameErr = $emailErr = $websiteErr = $genderErr = $commentErr = "";$name = $email = $website = $gender = $comment = "";$formIsValid = false; // Flag to check if form is valid overall
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate Name $name = sanitize_input($_POST["name"] ?? ''); if (empty($name)) { $nameErr = "Name is required"; } elseif (!preg_match("/^[pLs'-]+$/u", $name)) { $nameErr = "Only letters, spaces, hyphens, and apostrophes allowed"; }
// Validate Email $email = sanitize_input($_POST["email"] ?? ''); if (empty($email)) { $emailErr = "Email is required"; } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; }
// Validate Website (Optional) $website = sanitize_input($_POST["website"] ?? ''); if (!empty($website) && !filter_var($website, FILTER_VALIDATE_URL)) { $websiteErr = "Invalid URL format (include http:// or https://)"; }
// Validate Comment (Example: Check length) $comment = sanitize_input($_POST["comment"] ?? ''); if (strlen($comment) > 500) { // Example constraint $commentErr = "Comment cannot exceed 500 characters"; }
// Validate Gender (Assuming radio buttons with required selection) $gender = sanitize_input($_POST["gender"] ?? ''); if (empty($gender)) { $genderErr = "Gender is required"; } // Add specific checks if needed, e.g., ensure value is 'male', 'female', 'other'
// Check if all errors are empty if (empty($nameErr) && empty($emailErr) && empty($websiteErr) && empty($genderErr) && empty($commentErr)) { $formIsValid = true; // Process the valid data (e.g., save to database, send email) // echo "Form submitted successfully!"; // Optionally redirect or display success message } else { $formIsValid = false; // Errors exist, form will re-display with error messages }}
// Form HTML would go here, displaying $name, $email, etc. in input values// and $nameErr, $emailErr, etc. near the respective fields if they are not empty.?>
<!-- Example HTML Snippet --><!-- Make sure the form posts to the same PHP script --><form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, 'UTF-8'); ?>"> Name: <input type="text" name="name" value="<?php echo $name; ?>"> <span class="error">* <?php echo $nameErr; ?></span> <br><br>
E-mail: <input type="text" name="email" value="<?php echo $email; ?>"> <span class="error">* <?php echo $emailErr; ?></span> <br><br>
Website: <input type="text" name="website" value="<?php echo $website; ?>"> <span class="error"><?php echo $websiteErr; ?></span> <br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment; ?></textarea> <span class="error"><?php echo $commentErr; ?></span> <br><br>
Gender: <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male <input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other <span class="error">* <?php echo $genderErr;?></span> <br><br>
<input type="submit" name="submit" value="Submit"></form>
<style>.error { color: #FF0000; }</style>This example demonstrates retrieving data, sanitizing it, validating each field, storing error messages, and pre-filling the form with submitted values upon error. The htmlspecialchars($_SERVER["PHP_SELF"]) ensures the form submits to the current script securely.