1

I'm developing my web application which let user to upload file via a url. I want to know the file's size before I actually download whole contents because i want to limit size at 100MB.
How can I do this with curl in php or other suggest? Thanks.

<?php
$url = 'http://www.example.com/video.mp4';

$ch = curl_init($url);                 
curl_setopt($ch, CURLOPT_HEADER, 1);                
curl_setopt($ch, CURLOPT_TIMEOUT, 30);                 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

$size = // want to know file size here

if($size > 100 * 1024 * 1024) {
    echo "The file you're trying to uplaod is greater than 100MB, please try another.";
    exit;
}

file_put_contents(basename($url), file_get_contents($url));
?>
Marcus
  • 617
  • 2
  • 13
  • 19
  • 1
    Someone has already asked how to know the size of the file before downloading it: http://stackoverflow.com/a/2602624/4459298 – Saruva Nov 10 '15 at 16:54
  • Technically, you can't really do it in a safe way, the server you're asking for contents has to "play ball". This is usually done by server allowing you to perform a `HEAD` request which returns the meta-data about the resource (content length, content type, encoding etc). If the server is capable of only dumping the contents on you, then you're in problems because content-length can be `chunked` - meaning you can't safely determine how long it is. – Mjh Nov 10 '15 at 16:55
  • And just for your knowledge: use `copy` instead of `file_get_contents` + `file_put_contents` – kirugan Nov 10 '15 at 16:55
  • @kirugan - mind explaining why one should use something, so we don't have to google to justify your reasoning / suggestion? – Mjh Nov 10 '15 at 16:56
  • @Mjh, because it's faster and it`s more clear what you trying to do with your code. – kirugan Nov 10 '15 at 16:58
  • Thank you , i added `curl_setopt($ch, CURLOPT_NOBODY, true);` and it worked and get size from `curl_getinfo($fp, CURLINFO_CONTENT_LENGTH_DOWNLOAD)`; From this question http://stackoverflow.com/questions/2752482/curl-not-returning-content-length-header – Marcus Nov 10 '15 at 17:10
  • @Marcus I have an answer with a function that addresses a situation where HEAD requests are not supported - since this was closed I answered it here: http://stackoverflow.com/a/33636206/892493 It makes an HTTP requests with a Range header to request a 1 byte range of the file (most all media servers will respond appropriately to this). If a range response is not sent it looks for a content-length header. If neither is found the transfer is aborted. – drew010 Nov 10 '15 at 17:43

0 Answers0