Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get size of a remote file

Tags:

php

I want to get the size of a remote file. And it can be done via this code:

$headers = get_headers("http://addressoffile", 1);
$filesize= $headers["Content-Length"];

But i do not know the file address directly. But i have a address which redirects to the original file.

For example: I have address http://somedomain.com/files/34 When i put this address into url bar of browser or use function file_get_contents('myfile.pdf',"http://somedomain.com/files/34"); , it starts downloading the original file.

And if i use above functions for calculating size of file then using the address http://somedomain.com/files/34 it return size 0.

Is there any way to get the address where the http://somedomain.com/files/34 redirects .

Or any other solution for calculating the size of the redirected file(original file).

like image 422
Vinit Chouhan Avatar asked Sep 10 '25 19:09

Vinit Chouhan


1 Answers

If you want to get a remote file's size you need to think some other way. In this post I am going to show you how we can get a remote file's size from it's header information with out downloading file. I will show you two example. One, using get_headers function and another using cURL. Using get_headers is very simple approach and works for every body. Using cURL is more advance and powerful. You can use any one of these. But I recommend to use cURL approach. Here we go..

get_headers Approach:

/**
* Get Remote File Size
*
* @param sting $url as remote file URL
* @return int as file size in byte
*/
function remote_file_size($url){
# Get all header information
$data = get_headers($url, true);
# Look up validity
if (isset($data['Content-Length']))
    # Return file size
    return (int) $data['Content-Length'];
}

usage

echo remote_file_size('http://www.google.com/images/srpr/logo4w.png');

cURL Approach

/**
* Remote File Size Using cURL
* @param srting $url
* @return int || void
*/
function remotefileSize($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_exec($ch);
$filesize = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($ch);
if ($filesize) return $filesize;
}

usage

echo remotefileSize('http://www.google.com/images/srpr/logo4w.png');
like image 181
Prasanna Avatar answered Sep 13 '25 10:09

Prasanna