PHP Forms - Validate E-mail and URL

To validate E-mail and URL inputs in PHP forms, you can use the filter_var() function, which provides an easy way to validate data formats. Here's a simple example for both:


PHP Form Example with Email and URL Validation

<?php // Define variables and set to empty values $email = $website = ""; $emailErr = $websiteErr = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { // Email validation if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = test_input($_POST["email"]); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; } } // URL validation if (empty($_POST["website"])) { $websiteErr = "Website is required"; } else { $website = test_input($_POST["website"]); if (!filter_var($website, FILTER_VALIDATE_URL)) { $websiteErr = "Invalid URL format"; } } } // Helper function to sanitize inputs function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <!-- HTML Form --> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> Email: <input type="text" name="email" value="<?php echo $email;?>"> <span style="color:red;">* <?php echo $emailErr;?></span><br><br> Website: <input type="text" name="website" value="<?php echo $website;?>"> <span style="color:red;">* <?php echo $websiteErr;?></span><br><br> <input type="submit" name="submit" value="Submit"> </form>

Explanation:

  • filter_var($email, FILTER_VALIDATE_EMAIL): Checks if the input is a valid email address.

  • filter_var($website, FILTER_VALIDATE_URL): Checks if the input is a valid URL.

  • htmlspecialchars($_SERVER["PHP_SELF"]): Prevents XSS by escaping special characters in the form action.