PHP: Get the size of a remote file.

This is a guide on how to get the size of a remote file using PHP. In this guide, I will include both a cURL example and a non-cURL example. Both examples will attempt to get the size of the file without downloading it.

Warning: There is no surefire way to get the size of a remote file without downloading it. This method relies on the server in question returning a Content-Length header in the header response. Content-Length is an optional header for servers, which means that it might not be included.

Using cURL to get the size of a remote file.

If you would like to use PHP’s cURL extension to get the size of a remote file, you can use the following example:

In the PHP code above, we configured cURL to send a HEAD request to the remote file in question. We then extracted the Content-Length header by using the curl_getinfo function in conjunction with the CURLINFO_CONTENT_LENGTH_DOWNLOAD option.

Note that if the Content-Length header is not returned by the remote server, curl_getinfo will return a -1 (minus one).

You should also note that this is not a reliable way to check if a remote file exists. i.e. curl_getinfo could return -1 even if the resource in question exists. If you would like to check to see if the file actually exists or not, then you should read my guide on checking to see if a HTTP resource exists.

Using PHP’s get_headers function to get the size of a remote file.

If you do not have cURL installed, then you can use PHP’s inbuilt get_headers function:

In the PHP example above:

  1. We fetched the response headers for the resource in question by using PHP’s get_headers function. We passed in 1 as the second parameter. The second parameter tells get_headers to parse the response and set each header as an array key.
  2. For the sake of consistency, we converted all array keys to lower case by using the array_change_key_case function.
  3. We set the $fileSize variable to -1 by default. If the $fileSize variable is still -1, we will know that the Content-Length header was not returned by the server.
  4. We checked to see if the “content-length” key exists in our $headers array. Failing to use isset in this particular scenario may result in an undefined index warning. As stated above, the Content-Length header is optional.
  5. Finally, we dumped out the size of our remote file in bytes.

If you are wanting to get the size of a local file, then you should check out my tutorial on getting a file’s size in PHP.

Facebook Comments