iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Form URL/Email

URLs and emails are the two most common fields that need format validation. PHP ships filters for both.

Email

PHP
$email = trim($_POST['email'] ?? '');

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors['email'] = 'Invalid email';
}

URL

PHP
$url = trim($_POST['url'] ?? '');

if (!filter_var($url, FILTER_VALIDATE_URL)) {
    $errors['url'] = 'Invalid URL';
}

URL — require https

PHP
$url = trim($_POST['url'] ?? '');

if (!filter_var($url, FILTER_VALIDATE_URL) ||
    !str_starts_with($url, 'https://')) {
    $errors['url'] = 'URL must start with https://';
}

Sanitise to display

Validation answers "is this OK?". Sanitisation answers "make it safe to embed":

PHP
echo htmlspecialchars($email);     // safe in HTML
echo urlencode($email);            // safe in a URL
echo json_encode($email);          // safe in JSON

Caveats

  • FILTER_VALIDATE_EMAIL rejects some unusual but technically-legal email addresses. Good enough for 99% of forms.
  • Validation does not verify the address actually receives mail. For that, send a "click to confirm" link.
  • FILTER_VALIDATE_URL accepts schemes you might not want — javascript:, file:. Check the scheme explicitly.
Tip: Don't try to write your own email regex. The RFC is wild. Use the filter, or — for picky cases — a library like egulias/email-validator.

Example

Example
<?php
$url   = 'https://example.com';
$email = 'ada@example.com';
var_dump(filter_var($url, FILTER_VALIDATE_URL));
var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
Try it Yourself »

Exercise

URL validator filter constant.

filter_var($url, FILTER_VALIDATE _);

Test yourself

Q1. Validate URL with…
Q2. Accepting javascript: URL is…
Q3. Validation guarantees…

Discussion

Loading…