[PHP] – Check if a URL is valid/exists
- Posted in: Programming
Hello folks.
The following is a PHP function that will check a given URL to see if it’s valid, and check to see if it is responding (ie: returning Status: 200 OK).
First, the function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | function is_valid_url($url) { if (!($url = @parse_url($url))) { return false; } $url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port']; $url['path'] = (!empty($url['path'])) ? $url['path'] : '/'; $url['path'] .= (isset($url['query'])) ? "?$url[query]" : ''; if (isset($url['host']) AND $url['host'] != @gethostbyname($url['host'])) { if (PHP_VERSION >= 5) { $headers = @implode('', @get_headers("$url[scheme]://$url[host]:$url[port]$url[path]")); } else { if (!($fp = @fsockopen($url['host'], $url['port'], $errno, $errstr, 10))) { return false; } fputs($fp, "HEAD $url[path] HTTP/1.1\r\nHost: $url[host]\r\n\r\n"); $headers = fread($fp, 4096); fclose($fp); } return (bool)preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers); } return false; } |
How to use it? It’s simple.
1 2 3 4 5 6 7 8 | if (is_valid_url('http://google.com')) { echo 'sweetness!'; } else { echo 'awww damn, :('; } |
Enjoy
