Why can't I get the length of the iso file with `CURLINFO_CONTENT_LENGTH_DOWNLOAD` in php_curl?

I want to get the length of an iso file on the internet

http://cdimage.debian.org/debian-cd/8.0.0/i386/iso-cd/debian-8.0.0-i386-lxde-CD-1.iso

<?php
    $szUrl = 'http://cdimage.debian.org/debian-cd/8.0.0/i386/iso-cd/debian-8.0.0-i386-lxde-CD-1.iso';
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $szUrl);
    curl_setopt($curl, CURLOPT_HEADER, 1);
    curl_setopt($curl, CURLOPT_NOBODY, 1);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $size = curl_getinfo($curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
    echo $size;
?>

      

The result is -1 with code. How to get iso file length correctly using php_curl?
With Leggendario's answer, the key to my problem is setting CURLOPT_FOLLOWLOCATION to get the correct answer.
This makes my question different from http://stackoverflow.com/questions/2602612/php-remote-file-size-without-downloading-file

.

+3


source to share


1 answer


From the documentation

CURLINFO_CONTENT_LENGTH_DOWNLOAD

Pass pointer to double to get content length to download. This is the value read from the Content-Length: field. since 7.19.4, this returns -1 if the size is unknown.

You must first execute curl:

curl_exec($curl);

$size = curl_getinfo($curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
echo $size;

curl_close($curl);

      



But be careful because http://cdimage.debian.org/debian-cd/8.0.0/i386/iso-cd/debian-8.0.0-i386-lxde-CD-1.iso is just a redirect to http://gensho.acc.umu.se/debian-cd/8.0.0/i386/iso-cd/debian-8.0.0-i386-lxde-CD-1.iso. You can set the parameter CURLOPT_FOLLOWLOCATION

to true.

curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);

      

Otherwise, you will get the size of the redirect page.

+2


source







All Articles