Validating email addresses and website URLs ensures submitted data adheres to RFC standards and URL structure specifications. PHP's filter_var() function provides built-in validation flags for both formats.
FILTER_VALIDATE_EMAIL: Checks if string conforms to RFC 822 email format.FILTER_VALIDATE_URL: Checks if string conforms to URL structure syntax.FILTER_SANITIZE_EMAIL: Removes all illegal characters from email address string.FILTER_SANITIZE_URL: Removes all illegal characters from URL string.flowchart LR
A["Raw Input String"] --> B{"Choose Filter Task"}
B -- Sanitize Email --> C["filter_var($input, FILTER_SANITIZE_EMAIL)"]
B -- Validate Email --> D["filter_var($cleanEmail, FILTER_VALIDATE_EMAIL)"]
B -- Validate URL --> E["filter_var($url, FILTER_VALIDATE_URL)"]
D & E --> F["Returns Validated String or False"]
<?php
declare(strict_types=1);
function validateUserProfileForm(string $rawEmail, string $rawWebsite): array
{
$results = ['valid' => true, 'errors' => [], 'sanitized' => []];
// 1. Sanitize & Validate Email Address
$sanitizedEmail = filter_var(trim($rawEmail), FILTER_SANITIZE_EMAIL);
if (!filter_var($sanitizedEmail, FILTER_VALIDATE_EMAIL)) {
$results['valid'] = false;
$results['errors']['email'] = "Invalid email format (e.g. [email protected]).";
} else {
$results['sanitized']['email'] = $sanitizedEmail;
}
// 2. Sanitize & Validate Website URL
$sanitizedWebsite = filter_var(trim($rawWebsite), FILTER_SANITIZE_URL);
if (!filter_var($sanitizedWebsite, FILTER_VALIDATE_URL)) {
$results['valid'] = false;
$results['errors']['website'] = "Invalid URL syntax (e.g. https://kodersolution.com).";
} else {
$results['sanitized']['website'] = $sanitizedWebsite;
}
return $results;
}
// Test validation handler
$validation = validateUserProfileForm(" [email protected] ", "https://kodersolution.com");
if ($validation['valid']) {
echo "Form Validated Successfully!
";
echo "Clean Email: " . $validation['sanitized']['email'] . "
";
echo "Clean Website: " . $validation['sanitized']['website'] . "
";
}
FILTER_SANITIZE_EMAIL to clean whitespace before calling FILTER_VALIDATE_EMAIL.https:// Scheme on URLs: Use FILTER_FLAG_SCHEME_REQUIRED flag if your application requires valid HTTP/HTTPS protocols.filter_var() handles edge cases (like TLD extensions and IP domains) accurately compared to brittle custom regexes.Write a function isValidURL(string $url): bool that uses filter_var($url, FILTER_VALIDATE_URL) to return true if a URL is valid!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.