Entry
How do I get (ctime & mtime) on a remote file (http) without downloading it. "fstat", didn't help
Feb 24th, 2008 19:53
dman, Articles Way, Cinley Rodick, Gerhardt, Mikael Lirbank, http://www.ttnr.org
There's a suggestion in the PHP manual (look up "fstat"), but here's
an alternative. If it doesn't return a date, it's probably because the
server doesn't know (or I haven't read the RFC correctly).
It requires some code, but I tried to split it into 3 functions. The
function you need to use is getModified(). This code is a complete
example, and if you paste it into an empty .php file it should output
a date.
<?php
// This function returns an associative array returning any
// of the various components of the headers
function getHeaders($header) {
$lines = explode("\r\n",$header);
$headers = Array();
foreach($lines as $line) {
$header = explode(':',$line,2);
$name = strtolower($header[0]);
if(isset($header[1])) {
$headers[$name] = $header[1];
}
}
return $headers;
}
// Connects to URL using the HEAD method and returns headers
function connect($remote_file) {
$url = parse_url($remote_file);
$port = 80;
$path = $url['path'];
$host = $url['host'];
if(isset($url['port']) && !empty($url['port'])) {
$port = $url['port'];
}
if(!isset($url['path'])) {
$path = '/';
}
$fp = fsockopen($host, $port) or die("Could not
connect to $host");
fputs($fp,"HEAD $path HTTP/1.1\r\n");
fputs($fp,"Host: $host\r\n");
fputs($fp,"Connection: close\r\n\r\n");
$header = '';
while(!feof($fp)) {
$header .= fgets($fp,1024);
}
return $header;
}
// connects to URL and parses the headers
function getModified($remote_file) {
$date = '';
$response = connect($remote_file);
$headers = getHeaders($response);
if(isset($headers['last-modified'])) {
$date = $headers['last-modified'];
}
return $date;
}
// Example usage
$date = getModified("http://www.example.com/");
if(empty($date))
echo "Could not get date";
else
echo "Last modified: $date";
?>
======
brandonhutchinson.com/ctime_atime_mtime.html