FILTER_VALIDATE_URL constant in PHP

The FILTER_VALIDATE_URL constant validates a URL and returns the validated URL on success or FALSE on failure. It's commonly used with the filter_var() function to check if a string contains a valid URL format.

Syntax

filter_var($url, FILTER_VALIDATE_URL, $flags)

Parameters

  • $url − The URL string to validate

  • FILTER_VALIDATE_URL − The validation filter constant

  • $flags − Optional flags to specify additional requirements

Available Flags

  • FILTER_FLAG_SCHEME_REQUIRED − URL must be RFC compliant with a scheme (http, https, etc.)

  • FILTER_FLAG_HOST_REQUIRED − URL must include host name

  • FILTER_FLAG_PATH_REQUIRED − URL must have a path after the domain name

  • FILTER_FLAG_QUERY_REQUIRED − URL must have a query string

Return Value

Returns the validated URL on success, or FALSE on failure.

Basic URL Validation

Here's a simple example validating a valid URL ?

<?php
$url = "https://www.example.com";
$result = filter_var($url, FILTER_VALIDATE_URL);

if ($result) {
    echo "Valid URL: " . $result;
} else {
    echo "Invalid URL!";
}
?>
Valid URL: https://www.example.com

Invalid URL Example

Testing with an invalid URL format ?

<?php
$url = "examplecom";
$result = filter_var($url, FILTER_VALIDATE_URL);

if ($result) {
    echo "Valid URL: " . $result;
} else {
    echo "Invalid URL!";
}
?>
Invalid URL!

Using Flags

Example using flags to enforce specific URL requirements ?

<?php
$urls = [
    "example.com",
    "https://example.com",
    "https://example.com/path",
    "https://example.com/path?query=value"
];

foreach ($urls as $url) {
    echo "Testing: $url<br>";
    
    // Require scheme
    $result1 = filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED);
    echo "With SCHEME_REQUIRED: " . ($result1 ? "Valid" : "Invalid") . "<br>";
    
    // Require path
    $result2 = filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED);
    echo "With PATH_REQUIRED: " . ($result2 ? "Valid" : "Invalid") . "<br><br>";
}
?>
Testing: example.com
With SCHEME_REQUIRED: Invalid
With PATH_REQUIRED: Valid

Testing: https://example.com
With SCHEME_REQUIRED: Valid
With PATH_REQUIRED: Invalid

Testing: https://example.com/path
With SCHEME_REQUIRED: Valid
With PATH_REQUIRED: Valid

Testing: https://example.com/path?query=value
With SCHEME_REQUIRED: Valid
With PATH_REQUIRED: Valid

Conclusion

FILTER_VALIDATE_URL is essential for validating URL formats in PHP applications. Use flags to enforce specific URL requirements like schemes, paths, or query strings based on your application needs.

Updated on: 2026-03-15T07:34:05+05:30

563 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements