PHP

PHP PHP Form E-mail/URL


 

We have covered Validation of HTML Form & now let’s see validation in e-mails and URL

 

PHP – Validate E-mail

To validate an email address in PHP, you can use a combination of the ‘filter_var’ function and the ‘FILTER_VALIDATE_EMAIL’ filter.

 

Syntax:

<?php
    function isValidEmail($email) {
        // Use FILTER_VALIDATE_EMAIL filter
        return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
    }
?>

 

Example:

<?php
    // Example usage
    $email = "user@example.com";
    if (isValidEmail($email)) {
        echo "Valid email address";
    } else {
        echo "Invalid email address";
    }
?>

 

Output:

 

Alternative way to validate is by preg_match() function:

<?php
    function isValidEmail($email) {
        // Use preg_match to test the email against the pattern
        return preg_match( "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email) === 1;
    }
?>

 

PHP - Validate URL

The code below shows a simple way to check if the URL address is valid or not by using php predefined function ‘filter_var’.

 

Syntax:

<?php
    function isValidUrl($url) {
        // Use FILTER_VALIDATE_URL filter
        return filter_var($url, FILTER_VALIDATE_URL) !== false;
    }
?>

 

Example:

<?php
    $url = "http://www.example.com";
    if (isValidUrl($url)) {
        echo "Valid URL";
    } else {
        echo "Invalid URL";
    }
?>

 

By using preg_match() function:

<?php
    function isValidEmail($email) {
        // Use preg_match to test the email against the pattern
        return preg_match( "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email) === 1;
    }
?>