Skip to content
GreenSnippets

Validate emails and URLs in PHP

Use filter_var to validate email addresses and http(s) URLs, with an allow-list for schemes.

PHP
<?php
function isValidEmail(string $email): bool
{
    return strlen($email) <= 254 && filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

function isValidHttpUrl(string $url): bool
{
    if (filter_var($url, FILTER_VALIDATE_URL) === false) {
        return false;
    }
    return in_array(strtolower((string) parse_url($url, PHP_URL_SCHEME)), ['http', 'https'], true);
}

Example / expected output

Output
isValidEmail('ada@example.com');          // true
isValidHttpUrl('javascript:alert(1)');    // false

How it works

filter_var is stricter and safer than hand-written regular expressions. For URLs, FILTER_VALIDATE_URL accepts schemes like javascript: and file:, so check the scheme explicitly before storing or redirecting. A valid format does not prove the address exists; send a confirmation email for that.