To keep it short and sweet today, the following is a PHP function that will check the input for a valid URL, and will also check to see if it is responding (ie: returning Status: 200 OK).
UPDATES:
- December 01, 2024: Slight updates to code style and more “modern” PHP features (i.e.: PHP 7.4+). Also added an important note.
Note: This only checks if a given URL returns certain HTTP response/status codes. It considers a valid URL one that returns 200 OK, 301 Moved Permanently, or 302 Found.
With that being said, the function can be found below.
function isValidUrl(string $url): bool
{
if (!($url = @parse_url($url))) {
return false;
}
$url['port'] ??= 80;
$url['path'] = (!empty($url['path'])) ? $url['path'] : '/';
$url['path'] .= (isset($url['query'])) ? "?$url[query]" : '';
if (isset($url['host']) && $url['host'] !== @gethostbyname($url['host'])) {
$headers = get_headers(\sprintf('%s://%s:%d%s', $url['scheme'], $url['host'], $url['port'], $url['path']));
return (bool) preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers[0]);
}
return false;
}
How to use it? It’s simple.
if (isValidUrl('http://google.com')) {
echo 'sweetness!';
} else {
echo 'awww damn';
}
Enjoy 🙂
Can this be used to validate rss feeds too?
This can only be used to verify if a URL is valid, as far as returning a certain http code. In this case, it checks for 200 "OK", 301 "Permanent Redirect" or 302 "Moved Temporarily".
If you're looking to validate RSS feeds, as far as if their structure is valid – you'd want to use something like http://www.feedvalidator.org
Thank you for this!