note 28222 deleted from function.file-exists by sniper
| From: | sniper@php.net | Date: | Sun, 23 Nov 2003 01:27:52 +0000 |
| Subject: | note 28222 deleted from function.file-exists by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-60838@lists.php.net to get a copy of this message | ||
Note Submitter: river att clacks dott org
----
Re the function url_exists posted by conny at glidecom dot se in Feb 2002
This is a nice beginning but it can be improved.
Most important it is not very friendly to the internet to ask for a 20Mb file when you only want the
header. OK you only read the first 1024 bytes, but do you know how much of the file is being sent
by the far end before you do a close?
It is better to replace GET with HEAD. This gives you exactly the same headers as a GET, but does
not try to send you the actual file.
Much less important the documentation says to prefer preg_ functions to ereg functions.
Here is my coding based on Conny's original idea. Many thanks to Conny for starting me off.
Function url_header returns the headers for that url, and url_exists is true if exists and false
otherwise.
function url_header($url) {
$url = preg_replace('#^http:#i', '', $url);
if (preg_match('#^//#', $url)){
list(,,$domain, $file) = explode('/', $url, 4);
$file = "/$file";
} else {
$file = $url;
if (! preg_match('#^/#', $file)) $file = "/$file";
$domain = $_SERVER[HTTP_HOST];
}
$fid = fsockopen($domain, 80);
if (! $fid) return "Host not responding";
fputs($fid, "HEAD $file HTTP/1.0\r\nHost: $domain\r\n\r\n");
$head = fread($fid, 4096);
fclose($fid);
echo "<br>\n<pre>\n$head<pre>";
return $head;
}
function url_exists($url) {
return preg_match('#^HTTP/.*\s+200\sOK\s#i', url_header($url));
}
happy new year everyone!
River~~