Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CURL get file only if had been modified

how can I understand if a file was been modified before to open the stream with CURL (then I can open it with file-get-contents)

thanks

like image 549
user1638466 Avatar asked Sep 28 '12 08:09

user1638466


2 Answers

Check for CURLINFO_FILETIME:

$ch = curl_init('http://www.mysite.com/index.php');
curl_setopt($ch, CURLOPT_FILETIME, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
$exec = curl_exec($ch);

$fileTime = curl_getinfo($ch, CURLINFO_FILETIME);
if ($fileTime > -1) {
    echo date("Y-m-d H:i", $fileTime);
} 
like image 51
Mihai Iorga Avatar answered Oct 09 '22 03:10

Mihai Iorga


Try sending a HEAD request first to get the last-modified header for the target url for comparison of your cached version. Also you could try to use the If-Modified-Since header with the time your cached version is created with the GET request so the other side can respond you with 302 Not Modified too.

Sending a HEAD request with curl looks something like this:

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1);
$content = curl_exec($curl);
curl_close($curl)

The $content now will contain the returned HTTP header, as one long string, you can look for last-modified: in it like this:

if (preg_match('/last-modified:\s?(?<date>.+)\n/i', $content, $m)) {
    // the last-modified header is found
    if (filemtime('your-cached-version') >= strtotime($m['date'])) {
        // your cached version is newer or same age than the remote content, no re-fetch required
    }
}

You should handle the expires header too the same way (extract the value from the header string, check if if the value is in the future or not)

like image 1
complex857 Avatar answered Oct 09 '22 04:10

complex857