Home >Backend Development >PHP Tutorial >How Can I Get the Size of a Remote File Without Downloading It?
Determining Remote File Size
Getting the file size of a remote file without downloading it can be a useful optimization in certain scenarios.
Solution
As mentioned in the responses, using an HTTP HEAD request is a suitable approach for this task. HEAD requests retrieve the HTTP headers associated with a resource, without fetching the actual body.
Implementation
Here's a PHP function that leverages this method:
function get_remote_file_size($url) { $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_FOLLOWLOCATION, true); $data = curl_exec($curl); curl_close($curl); if ($data) { preg_match("/Content-Length: (\d+)/", $data, $matches); $content_length = $matches[1] ?? -1; return $content_length; } return -1; }
Usage
You can use this function to determine the size of a remote file:
$file_size = get_remote_file_size("http://my_url/my_file.txt");
Note: This method relies on the server honoring the HEAD request and providing the correct Content-Length header.
The above is the detailed content of How Can I Get the Size of a Remote File Without Downloading It?. For more information, please follow other related articles on the PHP Chinese website!