Validating names, email addresses, and website URLs in PHP forms requires strict server-side rules so malformed strings or dangerous javascript: links never reach your database. PHP's filter_var() handles email and URL syntax cleanly without brittle custom regular expressions.
FILTER_VALIDATE_EMAILWriting a custom regex for email addresses almost always rejects valid domains like .tech or emails with + tags. Use FILTER_VALIDATE_EMAIL after trimming whitespace and enforcing a maximum length (254 characters).
<?php
declare(strict_types=1);
function validateProfileLinks(string $name, string $email, string $website): array
{
$errors = [];
if (preg_match('/^[\p{L}\s\-\.']{2,80}$/u', trim($name)) !== 1) {
$errors['name'] = 'Enter a valid name using letters, spaces, or hyphens.';
}
$cleanEmail = trim($email);
if (strlen($cleanEmail) > 254 || !filter_var($cleanEmail, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Enter a valid email address.';
}
$cleanUrl = trim($website);
if ($cleanUrl !== '') {
$isValidUrl = filter_var($cleanUrl, FILTER_VALIDATE_URL) !== false;
$scheme = strtolower((string) parse_url($cleanUrl, PHP_URL_SCHEME));
if (!$isValidUrl || !in_array($scheme, ['http', 'https'], true)) {
$errors['website'] = 'Website URL must start with http:// or https://.';
}
}
return $errors;
}
print_r(validateProfileLinks("Nadia O'Connor", "[email protected]", "https://kodersolution.com"));
javascript: PayloadsFILTER_VALIDATE_URL accepts schemes like javascript:// or ftp:// because they are syntactically valid URIs. Always inspect parse_url($url, PHP_URL_SCHEME) and allow only http and https before rendering any user-submitted <a href="..."> link.
[a-zA-Z ]+ for international names: ASCII-only regexes reject valid accented or Unicode names like José or Øyvind. Use \p{L} with the /u modifier instead.FILTER_VALIDATE_URL: Without a scheme allowlist, malicious javascript: or data: links can slip into profile links.FILTER_SANITIZE_EMAIL: Removing invalid characters without warning can turn a typo into a different person's email. Reject invalid emails and ask the user to correct them.FILTER_VALIDATE_EMAIL guarantee an email inbox actually exists?No. It validates email syntax according to RFC rules. To verify inbox ownership, send a confirmation link with a one-time token.
FILTER_VALIDATE_URL plus parse_url() together?filter_var() verifies overall URL structure, while parse_url() lets you verify the protocol is strictly http or https.
checkdnsrr() verify a domain has mail records?Yes, checkdnsrr($domain, 'MX') checks DNS records, though network lookups add latency and can fail on temporary DNS hiccups.
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.
You've completed this section! Take a quick 5-question quiz to check your understanding.