How to find the download size of a file?

Submitted by: Muhammad
The question also asks us to find the total download size of a URL. But what if that URL passed into the script just points to a single file resource like a JPG file or a GIF file? Well, for a single file resource we just need to find the size of that particular file and then return it as the answer, and we are done. But, for an HTML document we will need to find the total size of all resources that are embedded and included on the page and return that as the answer - because you must remember that we want the total download size of a URL.

So, let's write a PHP function that will return the download size of a single file resource. How should we approach writing this function - what is the easiest way to find the download size of a single file resource on the web?

Well, there is an HTTP header called "Content-Length" which will actually tell us the size of a particular resource file in the HTTP response (after the resource is requested). So, all we have to do is use PHP's built in "get_headers" function, which will retrieve all the HTTP headers sent by the server in response to an HTTP request.

The get_headers function accepts a URL as an argument. So, the PHP code to retrieve the "Content-Length" header would look like this:

function get_remote_file_size($url) {
$headers = get_headers($url, 1);

if (isset($headers['Content-Length']))
return $headers['Content-Length'];

//checks for lower case "L" in Content-length:
if (isset($headers['Content-length']))
return $headers['Content-length'];

But, there is actually a problem with this code: you will not always receive the Content-Length header in an HTTP response. In other words, the HTTP Content-Length header is not guaranteed to be sent back by the web server hosting that particular URL, because it depends on the configuration of the server. This means that you need an alternative that always works in case the approach above fails.
Submitted by: Muhammad

Read Online Sr. PHP Programmer Job Interview Questions And Answers