W3docs

PHP Form Validation: URL and Email Inputs

Form validation is an important aspect of PHP web development, ensuring that the data entered by users is accurate and meets specific requirements before it is

Email and URL are two of the most common fields in any web form, and they are also two of the easiest for users to get wrong. A typo such as user@example (missing the top-level domain) or example.com (a URL with no scheme) will pass a naive "is it not empty" check but break the moment your application tries to send a message or follow the link.

This chapter shows how to validate email and URL inputs in PHP — confirming that a value has the expected shape before you store or use it. Validation is one step in a larger flow that also includes collecting the data from $_POST/$_GET, trimming it, and sanitizing it; see PHP Form Handling and PHP Form Validation for the full picture.

We cover two approaches: the built-in filter_var function (recommended) and regular expressions (useful to understand, occasionally needed for custom rules).

Validating Email Inputs

The cleanest way to validate an email address in PHP is the filter_var function with the FILTER_VALIDATE_EMAIL filter. It returns the filtered value if the string looks like a valid email, and false if it does not — so it pairs naturally with an if check:

php— editable, runs on the server

Because filter_var returns false (not null) for invalid input, always compare with the loose ! or strict === false. A common bug is writing if (filter_var($email, FILTER_VALIDATE_EMAIL) == false) for an address like 0, which is fine here, but in general prefer === false to avoid PHP's loose-comparison surprises.

Validating Email with a Regular Expression

You can also validate an email with a regular expression — a pattern that describes which strings are allowed — using preg_match. This is worth knowing, but reach for it only when you need a rule filter_var cannot express (for example, restricting to a single corporate domain):

php— editable, runs on the server

Note: Prefer FILTER_VALIDATE_EMAIL over a hand-written regex in production. The full email specification (RFC 5322) is notoriously hard to match with a single pattern, and the regex above will reject perfectly valid addresses such as long top-level domains (.museum) or +-tagged addresses ([email protected]). See PHP Regular Expressions if you want to dig into pattern syntax.

Validating URL Inputs

URLs are validated the same way, with filter_var and the FILTER_VALIDATE_URL filter. One important detail: the filter requires a scheme (http://, https://, ftp://, …). A bare example.com or www.example.com is reported as invalid, so decide up front whether your form expects users to type the https:// prefix.

php— editable, runs on the server

FILTER_VALIDATE_URL accepts extra flags to tighten the rule — for example, FILTER_FLAG_PATH_REQUIRED (the URL must contain a path after the host) or FILTER_FLAG_QUERY_REQUIRED (it must contain a query string):

<?php
  $url = "https://example.com/page?ref=newsletter";
  if (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED)) {
    echo "Valid URL with a query string";
  } else {
    echo "Missing or invalid query string";
  }
?>

Validating URL with a Regular Expression

As with email, you can match a URL with a regular expression. The pattern below is permissive and best treated as a learning aid rather than a production rule:

php— editable, runs on the server

Note: For both email and URL, the built-in filter_var filters are the recommended choice. They are maintained alongside PHP, cover edge cases regex misses, and read far more clearly in your code.

Putting It Together in a Form

In a real form you do not work with hard-coded strings — you read the submitted values from the $_POST superglobal, trim them, and collect any errors so you can show them all at once. This example validates a required email and an optional website:

<?php
  // Imagine these come from a submitted <form method="post">.
  $email   = trim($_POST["email"] ?? "");
  $website = trim($_POST["website"] ?? "");

  $errors = [];

  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Please enter a valid email address.";
  }

  // Website is optional: only validate it when something was typed.
  if ($website !== "" && !filter_var($website, FILTER_VALIDATE_URL)) {
    $errors[] = "Please enter a valid URL.";
  }

  if (empty($errors)) {
    echo "All inputs are valid.";
  } else {
    echo implode("\n", $errors);
  }
?>

The ?? "" null-coalescing operator avoids a warning when the field is missing, and the $website !== "" check makes the URL optional. This is the same pattern used in PHP Form Required Fields.

Validation vs. Sanitization

Validation answers "does this value have the right shape?" — it does not strip or escape dangerous characters. Sanitization does that. PHP exposes sanitizing filters such as FILTER_SANITIZE_EMAIL, which removes characters that are not allowed in an email address:

<?php
  $raw   = "user(at)example.com";
  $clean = filter_var($raw, FILTER_SANITIZE_EMAIL); // "useratexample.com"

  if (filter_var($clean, FILTER_VALIDATE_EMAIL)) {
    echo "Usable email: $clean";
  } else {
    echo "Could not produce a valid email";
  }
?>

Here sanitizing turns user(at)example.com into useratexample.com, which then fails validation — exactly the right outcome, since the original was not a real address. As a rule: validate to accept or reject, sanitize before output, and never trust input from a form. For escaping data on its way into HTML or a database, see htmlspecialchars and mysqli::real_escape_string.

Summary

  • Use filter_var($value, FILTER_VALIDATE_EMAIL) and filter_var($value, FILTER_VALIDATE_URL) for reliable, readable validation.
  • FILTER_VALIDATE_URL requires a scheme such as https://; add flags like FILTER_FLAG_PATH_REQUIRED to tighten the rule.
  • Regular expressions can validate these formats too, but they are easy to get wrong — prefer the built-in filters.
  • Validation and sanitization are different jobs; use both, and treat all submitted data as untrusted.

Practice

Practice
Which of the following statements about PHP form, URL, and E-mail are correct?
Which of the following statements about PHP form, URL, and E-mail are correct?
Was this page helpful?