Search the blog

PHP doesn't actually have a URL path validation function but it does have a URL validation function. So, to validate a path all you need to do a prepend any domain onto your path. The results in a path validation function like this:

function validateURLPath($path) {

    $result = filter_var('http://www.example.com' . $path, FILTER_VALIDATE_URL);
    
    if ($result === false) {

        return false;

    } else {

        return true;

    }

}

var_dump(validateURLPath('Not a valid path')); // false
var_dump(validateURLPath('/root-relative-path.html?foo=bar')); // true

Note that for it to be a path it should start with a forward slash. Something like page.html is part of the path but not an entire path. To validate these you should first prepend a forward slash.

Tim Bennett is a web designer and developer. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.