How to Get remote file size using PHP

By | July 10, 2015

How to Get remote file size using PHP

[dropcap]I[/dropcap]n some cases we need to know the file size of a file before downloading it. Let’s see how we can do it using php. To to get remote file size using php we can use curl method.

For example, Let’s see how we can get the file size of a url using php and curl.

First we need to make curl connection with some options,
$ch = curl_init('http://www.google.co.in/images/srpr/logo4w.png');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_NOBODY, TRUE);

CURLOPT_RETURNTRANSFER = True is used to return the transfer as a string
CURLOPT_HEADER – True includes header in the output
CURLOPT_NOBODY = True will exclude the body from the output.

Execute the curl request,
curl_exec($ch);

Then to get the size of a file use the below function,
$filesize = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);

close the curl connection,
curl_close($ch);
echo $filesize;

Full code snippet to get remote file size using PHP

$ch = curl_init('http://www.google.co.in/images/srpr/logo4w.png');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_NOBODY, TRUE);
curl_exec($ch);
$filesize = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($ch);
echo $filesize;

🔥0

Leave a Reply