PHP Forms – Validate E-mail and URL

Welcome to The Coding College! In this tutorial, we’ll explore how to validate E-mail and URL fields in PHP forms. These fields are often critical for collecting accurate and trustworthy user information, and PHP provides powerful tools to validate them.

Why Validate E-mails and URLs?

Validation ensures the data users enter into forms meets specific criteria. For e-mails and URLs:

  1. E-mail Validation ensures you collect properly formatted and functional email addresses.
  2. URL Validation ensures web links provided by users are correctly structured.

Validation prevents data issues and enhances security by blocking malicious inputs.

PHP’s Built-in Tools for Validation

  1. filter_var(): PHP provides the filter_var() function for validating both email addresses and URLs.
    • E-mail Validation: FILTER_VALIDATE_EMAIL
    • URL Validation: FILTER_VALIDATE_URL
  2. Regular Expressions (Optional): If you need custom validation beyond the standard formats.

Example: Form to Validate E-mail and URL

HTML Form

<!DOCTYPE html>
<html lang="en">
<head>
    <title>PHP Form Validation: E-mail and URL</title>
</head>
<body>
    <h2>PHP Form Validation Example</h2>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        E-mail: <input type="text" name="email">
        <span style="color:red;">* <?php echo $emailErr ?? ''; ?></span>
        <br><br>
        
        Website URL: <input type="text" name="url">
        <span style="color:red;">* <?php echo $urlErr ?? ''; ?></span>
        <br><br>
        
        <button type="submit">Submit</button>
    </form>
</body>
</html>

PHP Script to Validate E-mail and URL

<?php
// Initialize variables
$email = $url = "";
$emailErr = $urlErr = "";

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate E-mail
    if (empty($_POST["email"])) {
        $emailErr = "E-mail is required";
    } else {
        $email = test_input($_POST["email"]);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Invalid e-mail format";
        }
    }

    // Validate URL
    if (empty($_POST["url"])) {
        $urlErr = "URL is required";
    } else {
        $url = test_input($_POST["url"]);
        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            $urlErr = "Invalid URL format";
        }
    }

    // Display data if validation is successful
    if (empty($emailErr) && empty($urlErr)) {
        echo "<h3>Form Submitted Successfully!</h3>";
        echo "E-mail: $email <br>";
        echo "URL: $url <br>";
    }
}

// Function to sanitize input
function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>

How This Example Works

  1. Sanitize Input:
    • The test_input() function removes unnecessary spaces, slashes, and converts special characters to HTML entities.
  2. E-mail Validation:
    • filter_var($email, FILTER_VALIDATE_EMAIL) checks the input against a standard email format (e.g., [email protected]).
    • If invalid, it sets an error message.
  3. URL Validation:
    • filter_var($url, FILTER_VALIDATE_URL) ensures the input matches a valid URL structure (e.g., https://www.example.com).
    • If invalid, it sets an error message.
  4. Error Feedback:
    • Errors are displayed next to the respective fields to guide users.
  5. Display Data:
    • If all inputs are valid, the submitted data is displayed.

Examples of Valid and Invalid Inputs

Valid E-mails

Invalid E-mails

  • example.com (missing @)
  • user@domain (missing .com or .org)

Valid URLs

  • https://www.example.com
  • http://example.org/page

Invalid URLs

  • www.example.com (missing http:// or https://)
  • example (not a valid URL)

Enhancing Validation with Regular Expressions (Optional)

For advanced requirements, you can use Regular Expressions (regex) for custom validation.

E-mail Validation Regex

if (!preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email)) {
    $emailErr = "Invalid e-mail format";
}

URL Validation Regex

if (!preg_match("/\b((https?|ftp):\/\/[-a-zA-Z0-9+&@#\/%?=~_|!:,.;]*)/", $url)) {
    $urlErr = "Invalid URL format";
}

Best Practices for Validating E-mails and URLs

  1. Always Use Server-Side Validation:
    • Even if client-side validation exists, PHP ensures the data is valid before processing.
  2. Sanitize Inputs:
    • Use filter_var() or custom sanitization to remove malicious input.
  3. Provide Clear Error Messages:
    • Display meaningful error messages near the fields to guide users.
  4. Use HTTPS:
    • When accepting URLs, recommend secure (HTTPS) links.

Real-World Use Cases

  1. Registration and Login Forms:
    • Validate e-mails for user accounts to prevent invalid or fake accounts.
  2. Contact Forms:
    • Ensure e-mails and website links are valid for follow-ups.
  3. API Inputs:
    • Validate URLs when accepting data from third-party integrations.

Conclusion

Validating e-mails and URLs in PHP forms is essential for collecting accurate and secure user input. Using PHP’s filter_var() function simplifies validation while ensuring robust security.

For more tutorials, tips, and coding resources, visit The Coding College. Keep learning, coding, and building amazing applications! 🚀

Leave a Comment