Another method for checking whether a URL exists
In a previous article we demonstrated a simple method for discovering whether or not a URL exists. The following code accomplishes the same thing, but offers a little more control.
/* Brendan Warkentin */ /* urlexists($url, $port = 80, $codes = array(200), $ssl = false) * * @Description: * Determine whether a url really exists. * * @Parameters: * $url:string - The fully-qualified url to check. * $port:int - The port to connect to. * $codes:array - The return codes to look for. * $ssl:bool - Whether we should use an encrypted connection. * * @Return: * Bool. True if the url exists, false otherwise. * * @Misc * By default this only checks for a return code of 200(OK). Some sites * do redirecting, and usually return 302. If you would like it to check * that you will have to manually specify the codes to check. */ function urlexists($url, $port = 80, $codes = array(200), $ssl = false) { $host = parse_url($url, PHP_URL_HOST); $path = parse_url($url, PHP_URL_PATH); $path = (strstr($path, "/") === 0 ? $path : "/"); $req = sprintf("GET %s HTTP/1.0rnHost: %srnrn", $path, $host); $sock = false; $found = false; if ($ssl) $sock = fsockopen("ssl://".$host, $port); else $sock = fsockopen($host, $port); if ($sock != false) { fputs($sock, $req); $ret = fgets($sock); fclose($sock); foreach ($codes as $i) if (strstr($ret, (string) $i) !== false) $found = true; return $found; } return false; }