无法使用CURL将文件下载到我的上传目录

时间:2014-07-09 06:23:06

标签: php curl

我正在尝试使用curl下载源文件,但它只创建0字节的目标文件,而不是下载原始文件并写入资源数据。我怎么解决这个问题。我在此链接中尝试了一个示例:http://www.w3bees.com/2013/09/download-file-from-remote-server-with.html。但它也会给出相同的结果。

有人可以帮忙吗?我的代码是:

if(isset($_POST[$data_file_name_url])){
        $source = 'http://mr-greens-class.wikispaces.com/file/messages/Calender.ics';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $source);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSLVERSION,3);
        $data = curl_exec ($ch);
        $error = curl_error($ch);
        curl_close ($ch);

        $destination = $dir.'/test.ics';
        $file = fopen($destination, "w+");
        fputs($file, $data);
        //file_put_contents($destination, $data);
        fclose($file);
    }

1 个答案:

答案 0 :(得分:0)

如果不使用,你应该删除SSLVERSION(你的URL以http开头,所以我认为它不是SSL)

$path = 'myfile.ics';
$final_url = 'http://mr-greens-class.wikispaces.com/file/messages/Calender.ics';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $final_url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
//curl_setopt($ch, CURLOPT_PORT, 80);
curl_setopt($ch, CURLOPT_HEADER, 0);

// sometimes needed to prevent problem by bot filtering
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.103 Safari/537.36'); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($ch);
if($data == false) {
        $errno = curl_errno($ch);
        $error_message = curl_error($ch);
        //error_log( "cURL error ({$errno}):\n<br/> {$error_message}");
}
curl_close($ch);

file_put_contents($path, $data);