7

我想用 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); 
    }

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

4

3 回答 3

4

你可以试试 CURLOPT_FOLLOWLOCATION

TRUE 跟随服务器作为 HTTP 标头的一部分发送的任何“Location:”标头(注意这是递归的,PHP 将跟随它发送的尽可能多的“Location:”标头,除非设置了 CURLOPT_MAXREDIRS)。

所以它会导致:

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); 
}
于 2012-07-06T22:02:33.437 回答
2

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

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

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

于 2012-07-06T22:04:55.167 回答
1

哦!

CURLOPT_FOLLOWLOCATION 工作完美......

The problem is that I use CURLOPT_URL for fopen(), I simply change CURLOPT_URL whit CURLOPT_FILE

and it works very well! thank you for your help =)

于 2012-07-06T22:53:54.650 回答