2

I want to get the length of the iso file on the web

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 output is -1 with the code,How to get the length of the iso file properly with php_curl?
With the answer of Leggendario , the key of my problem is to set CURLOPT_FOLLOWLOCATION to get right answer.
It makes my question different from the http://stackoverflow.com/questions/2602612/php-remote-file-size-without-downloading-file.

showkey
  • 482
  • 42
  • 140
  • 295

1 Answers1

1

From the documentation

CURLINFO_CONTENT_LENGTH_DOWNLOAD

Pass a pointer to a double to receive the content-length of the download. This is the value read from the Content-Length: field. Since 7.19.4, this returns -1 if the size isn't known.

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 redirection to http://gensho.acc.umu.se/debian-cd/8.0.0/i386/iso-cd/debian-8.0.0-i386-lxde-CD-1.iso. You may want set CURLOPT_FOLLOWLOCATION to true.

curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);

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

Federkun
  • 36,084
  • 8
  • 78
  • 90