php curl下载文件

时间:2018-01-07 20:36:02

标签: php curl

我需要通过curl下载文件并将其保存在服务器上。第二次,我将点击文件下载URL,我应该在我自己的服务器上启动。 我的代码如下:

$output_filename = "file.zip";
$host = $_GET['link'];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, false);
curl_setopt($ch, CURLOPT_REFERER, "http://your-site.url");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
curl_setopt($ch, CURLOPT_HEADER, 0);
$agents = array(
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101     Firefox/7.0.1',);
curl_setopt($ch,CURLOPT_USERAGENT,$agents[array_rand($agents)]);
$result = curl_exec($ch);
curl_close($ch);

header('Content-Disposition: attachment; filename ="file.zip"');
print_r($result); // prints the contents of the collected file before writing..

1 个答案:

答案 0 :(得分:0)

如果我解释这是正确的,你想构建类似缓存的东西,你从远程服务器下载文件x一次,之后文件应该从你自己的服务器提供?

如果是这种情况,这可能是解决问题的好方法:

class Downloader
{

    private $path;
    public $filename;

    public function __construct()
    {
        $this->path = dirname(__FILE__);
    }

    public function getFile($url)
    {
        $fileName = $this->getFileName($url);
        if(!file_exists($this->path."/".$fileName)){
            $this->downloadFile($url,$fileName);
        }

        return file_get_contents($this->path."/".$fileName);
    }


    public function getFileName($url)
    {
        $slugs = explode("/", $url);
        $this->filename = $slugs[count($slugs)-1];
        return $this->filename;
    }

    private function downloadFile($url,$fileName)
    {
        //This is the file where we save the information
        $fp = fopen ($this->path.'/'.$fileName, 'w+');
        //Here is the file we are downloading, replace spaces with %20
        $ch = curl_init(str_replace(" ","%20",$url));
        curl_setopt($ch, CURLOPT_TIMEOUT, 50);
        // write curl response to file
        curl_setopt($ch, CURLOPT_FILE, $fp); 
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        // get curl response
        curl_exec($ch); 
        curl_close($ch);
        fclose($fp);
    }

}


$downloader = new Downloader();
$content = $downloader->getFile("YOUR URL");

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$downloader->filename.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . mb_strlen($content));
print $content;
exit;

这是一个非常基本的概念,有很多要点必须根据您的使用情况进行改进和定制。