D
D
denisyukphp2016-03-21 23:07:24
PHP
denisyukphp, 2016-03-21 23:07:24

Can HTTP headers be relied upon to determine the size of a remote file?

I'm working on a small project in which I need to implement the loading of images from the local machine and by URL. Before uploading images, I would like to check their size. In the case of uploading from a browser, you can rely on $_FILES['upload']['size'] or filesize(), and for URLs, the first thing that comes to mind is to check HTTP headers. Obviously, the headers can be changed, but downloading the entire file to the server or to a variable for validation is not comme il faut, because. long and costly.

$ch = curl_init('http://i.imgur.com/VpDM99Ob.jpg');
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

The curl_getinfo() function returns an associative array with various values, among which is "download_content_length" (the size of the downloaded data, read from the "Content-Length" header).
Array
(
    [url] => 'http://i.imgur.com/VpDM99Ob.jpg',
    [content_type] => 'image/jpeg',
    [http_code] => 200,
    [download_content_length] => 6300,
    /* ... */
)

The value of "download_content_length" can be -1 if the HTTP header "Content-Length" is not set, but in this case we can invalidate that it is not an image hiding behind the searched URL, because all servers tend to give "Content-Length" and "Content-Type" to the binary files, unless there is some shenanigans.
- Is it possible to determine the size of the downloaded file by URL in this way? What alternative solutions still exist for pictures and files in particular?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
justpusher, 2016-03-26
@denisyukphp

The question boils down to this: does the remote server always send the correct Content-Length? we cannot be 100% sure of this.
From what I understand, you want to limit the maximum size of uploaded pictures.
You can do this:
1. Request headers. If there is more Content-Length, reject it right away.
2. Request content, controlling the size of the received data. As soon as you get more data than your limit, you cut off the request and reject it. Here is an example.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question