Header Only Retrieval in PHP via cURL
Introduction
In certain scenarios, retrieving only the HTTP headers of a remote resource can provide performance benefits. This article explores the advantages of header-only retrieval and offers a PHP cURL solution to retrieve the last modified date of a remote file.
Processing Power and Bandwidth Savings
When fetching only the headers, the remote server incurs less processing overhead compared to returning the entire page. Similarly, the network bandwidth consumption is reduced, which can be beneficial for low-bandwidth connections or situations where preserving bandwidth is crucial.
Retrieving Last Modified Date
To obtain the last modified date or If-Modified-Since header, cURL's CURLOPT_FILETIME and CURLOPT_NOBODY options can be utilized. These settings instruct cURL to retrieve only the filetime information and skip downloading the page content.
Example Implementation
class LastChange { public $lastChange; function setLastChange() { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, "http://url/file.xml"); curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_FILETIME, true); curl_setopt($curl, CURLOPT_NOBODY, true); $header = curl_exec($curl); $this->lastChange = curl_getinfo($curl, CURLINFO_FILETIME); curl_close($curl); } function getLastChange() { return $this->lastChange; } }
By passing CURLINFO_FILETIME as the second parameter to curl_getinfo(), the last modified date is retrieved as a Unix timestamp.
Additional Considerations
However, it's important to note that filetime information may not always be available. In such cases, curl_getinfo() will return -1, indicating that the filetime could not be determined.
The above is the detailed content of How Can I Efficiently Retrieve the Last Modified Date of a Remote File in PHP using cURL?. For more information, please follow other related articles on the PHP Chinese website!