note 28222 added to function.file-exists
| From: | river at rack1 dot php dot net | Date: | Mon, 06 Jan 2003 15:46:57 +0000 |
| Subject: | note 28222 added to function.file-exists | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-41733@lists.php.net to get a copy of this message | ||
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~~
--
http://www.php.net/manual/en/function.file-exists.php
http://master.php.net/manage/user-notes.php?action=edit+28222
http://master.php.net/manage/user-notes.php?action=delete+28222
http://master.php.net/manage/user-notes.php?action=reject+28222