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
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);
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With