CURL receives a file only if it has been modified

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

thanks

+4
source share
2 answers

Check out 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("Ymd H:i", $fileTime); } 
+3
source

Try sending a HEAD request first to get the last-modified header for the destination URL to compare your cached version. You can also try using the If-Modified-Since header over time, when your cached version will be created using a GET request so that the other side can also respond to you with 302 Not Modified .

Sending a HEAD request using 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) 

Now $content will contain the returned HTTP header, as one long string, you can search last-modified: as follows:

 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 also handle the expires header (extract the value from the title bar, check if the value is in the future or not)

+1
source

Source: https://habr.com/ru/post/1436765/


All Articles