Home >Backend Development >PHP Tutorial >How Can I Get the Size of a Remote File Without Downloading It?

How Can I Get the Size of a Remote File Without Downloading It?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-18 09:33:10172browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn