Validate emails and URLs in PHP
Use filter_var to validate email addresses and http(s) URLs, with an allow-list for schemes.
- PHP
- GreenSnippets
- MIT
- Executed with PHP 8.2
<?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
isValidEmail('ada@example.com'); // true
isValidHttpUrl('javascript:alert(1)'); // falseHow 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.
Related snippets
- Python Tested
Sign API requests with HMAC-SHA256
Create and verify a timestamped signature over the method, path and body so requests cannot be forged or replayed.
- JavaScript Tested
Generate secure random IDs and integers
Create UUIDs, random integers in a range and URL-safe tokens with the Web Crypto API instead of Math.random.
- PHP Tested
Generate a secure random token in PHP
Create unpredictable tokens for password resets, API keys and CSRF protection with random_bytes.
- PHP Tested
Escape output to prevent XSS in PHP
A short helper around htmlspecialchars with the right flags for HTML text and attribute values.

