使用url var下载文件Curl

Jul*_*ien 7 php curl

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

http://localhost/download.php?id=13456
Run Code Online (Sandbox Code Playgroud)

当我尝试使用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); 
    }
Run Code Online (Sandbox Code Playgroud)

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

Ham*_*mZa 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); 
}
Run Code Online (Sandbox Code Playgroud)