Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download file Curl with url var

Tags:

php

curl

I would like to download a file with Curl. The problem is that the download link is not direct, for example:

http://localhost/download.php?id=13456

When I try to download the file with curl, it download the file download.php!

Here is my curl code:

        ###
        function DownloadTorrent($a) {
                    $save_to = $this->torrentfolder; // Set torrent folder for download
                    $filename = str_replace('.torrent', '.stf', basename($a));

                    $fp = fopen ($this->torrentfolder.strtolower($filename), 'w+');//This is the file where we save the information
                    $ch = curl_init($a);//Here is the file we are downloading
                    curl_setopt($ch, CURLOPT_ENCODING, "gzip"); // Important 
                    curl_setopt($ch, CURLOPT_TIMEOUT, 50);
                    curl_setopt($ch, CURLOPT_URL, $fp);
                    curl_setopt($ch, CURLOPT_HEADER,0); // None header
                    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); // Binary trasfer 1
                    curl_exec($ch);
                    curl_close($ch);
                    fclose($fp); 
    }

Is there a way to download the file without knowing the path?

like image 773
Julien Avatar asked Jul 06 '12 21:07

Julien


1 Answers

You may try CURLOPT_FOLLOWLOCATION

TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).

So it will result into:

function DownloadTorrent($a) {
    $save_to = $this->torrentfolder; // Set torrent folder for download
    $filename = str_replace('.torrent', '.stf', basename($a));

    $fp = fopen ($this->torrentfolder.strtolower($filename), 'w+');//This is the file where we save the information
    $ch = curl_init($a);//Here is the file we are downloading
    curl_setopt($ch, CURLOPT_ENCODING, "gzip"); // Important 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 50);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER,0); // None header
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); // Binary transfer 1
    curl_exec($ch);
    curl_close($ch);
    fclose($fp); 
}
like image 144
HamZa Avatar answered Sep 21 '22 01:09

HamZa