Get remote file size

I want to get the size of the deleted file. And this can be done with this code:

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

But I do not know the address of the file directly. But I have an address that is redirected to the source file.

For example: I have an address. http://somedomain.com/files/34 When I put this address in the browser url string or use a function file_get_contents('myfile.pdf',"http://somedomain.com/files/34");, it starts loading the source file.

And if I use the functions above to calculate the file size, then using the address http://somedomain.com/files/34, it returns a size of 0.

Is there any way to get the address that is being redirected to http://somedomain.com/files/34.

Or any other solution to calculate the size of the redirected file (source file).

+3
source share
3 answers

. , :

// get the redirect url
$headers = get_headers("http://somedomain.com/files/34", 1);
$redirectUrl = $headers['Location'];

// get the filesize
$headers = get_headers($redirectUrl, 1);
$filesize = $headers["Content-Length"];

, , .

+3

, . , . . , get_headers, - cURL. get_headers - . cURL . . cURL. ..

get_headers :

/**
* 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'];
}

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

cURL

/**
* 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;
}

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

The cURL approach is good because it get_headersturns off on some servers . But if your url has http, httpsand ..., you need this:

<?php

function remotefileSize($url)
{
    //return byte
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
    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;
}

$url = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
echo remotefileSize($url);

?>
0
source

Source: https://habr.com/ru/post/1679802/


All Articles