bhylu.com

Advertisements

PHP URL and Email Validation

An email-shaped string and a URL-shaped string need different rules. Validation checks a format; it does not prove delivery, ownership or permission to contact a destination.

How it works

FILTER_VALIDATE_EMAIL checks an email representation without sending mail. A URL parser can expose a scheme and host for an allowlist policy. Encoding a URL into an HTML attribute is a later step and does not remove a dangerous scheme. Do not fetch arbitrary visitor-supplied URLs from a server: a syntactically valid URL can still point to a private service or an unapproved destination.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l url-email-validation.php
php url-email-validation.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · url-email-validation.php

<?php
declare(strict_types=1);

$email = "reader@example.test";
echo filter_var($email, FILTER_VALIDATE_EMAIL) !== false ? "Email-shaped value\n" : "Invalid format\n";
$url = "https://library.example.test/catalogue";
$parts = parse_url($url);
$allowed = is_array($parts) && ($parts["scheme"] ?? "") === "https" && ($parts["host"] ?? "") === "library.example.test";
echo $allowed ? "Approved link host\n" : "Rejected destination\n";

Expected result

Email-shaped value
Approved link host

Both results are local checks against fictional data. No email is delivered and no URL is fetched. A real application may need an email confirmation flow or a much stricter server-fetch policy with DNS/IP and redirect handling; this link-host example does not implement those systems.

Check the official PHP manual for detailed version and API contracts.