问题
As the name suggests, is there a quick way to download a file, but bring the timestamp along?
I'm writing a basic cache that, among other checks, determines (via get_headers
) if a given local file is the same as it's remote counterpart.
I know I can file_get_contents
/ file_put_contents
and then touch()
the file with the results of get_headers
, but the calling that is making another HTTP call (even if it is a HEAD call) and I'd only like to test Last-Modified as a last resort.
So is there a quick, "one HTTP call" way to download a file and preserve the timestamp? Some remote files live on an FTP server, but many are text files, and / or live on a web server.
EDIT: Someone suggested a related question, but my question differs, in that I'm looking to get the remote modified date without having to make a second call, which the copy()
based answer suggests
$http_response_header
seems to do the trick, as suggested below.
回答1:
You can get cached Last-Modified
from $http_response_header and use it to touch the file.
To automate it completely is obviously not possible as the stream cannot know where are you going to store it.
回答2:
You can use filemtime() to get last modified date and then touch() for modifying last modified date/time
Source: PHP copy file without changing the last modified date
回答3:
if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 60 * 5 ))) {
// Cache file is less than five minutes old.
// Don't bother refreshing, just use the file as-is.
$file = file_get_contents($cache_file);
} else {
// Our cache is out-of-date, so load the data from our remote server,
// and also save it over our cache for next time.
$file = file_get_contents($url);
file_put_contents($cache_file, $file, LOCK_EX);
}
来源:https://stackoverflow.com/questions/35083308/php-download-file-and-preserve-timestamp