使用url var下载文件Curl

时间:2012-07-06 21:52:25

标签: php curl

我想用Curl下载一个文件。 问题是下载链接不是直接的,例如:

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

当我尝试使用curl下载文件时,它会下载文件download.php!

这是我的卷曲代码:

        ###
        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); 
    }

有没有办法在不知道路径的情况下下载文件?

3 个答案:

答案 0 :(得分:4)

您可以尝试CURLOPT_FOLLOWLOCATION

  

TRUE以跟随服务器作为部分发送的任何“Location:”标头   HTTP标头(注意这是递归的,PHP将遵循尽可能多的   除非CURLOPT_MAXREDIRS是,否则“Location:”标题将被发送   设定)。

所以它会导致:

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); 
}

答案 1 :(得分:2)

将FOLLOWLOCATION选项设置为true,例如:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

选项记录在此处:http://www.php.net/manual/en/function.curl-setopt.php

答案 2 :(得分:1)

噢!

CURLOPT_FOLLOWLOCATION工作完美...

问题是我对fopen()使用 CURLOPT_URL ,我只需更改 CURLOPT_URL whit CURLOPT_FILE

它运作良好! 谢谢你的帮助=)