如何使用php下载文件,提供的路径是已知的


How to download a file using php, Provided path is known

我必须从web源下载与数据相关的pdf文件。我知道文件的完整路径。我尝试过使用curl,但它需要很长时间,并且需要编写一个0字节的文件。

$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata = curl_exec($ch);
curl_close ($ch);
if(file_exists($fullpath)){
    unlink($fullpath);
}
$fp = fopen($fullpath,'x');
fwrite($fp, $rawdata);
fclose($fp);
$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

http://www.php.net/manual/en/curl.examples-basic.php

或者使用这个(如果在PHP conf中设置了fopen包装器):

$file = 'http://somehosted.com/file.pdf'; // URL to the file
$contents = file_get_contents($file); // read the remote file
touch('somelocal.pdf'); // create a local EMPTY copy
file_put_contents('somelocal.pdf', $contents); // put the fetchted data into the newly created file
// done :)

这个可能最适合你:http://www.jonasjohn.de/snippets/php/curl-example.htm

很难说你的代码是什么样子的,哪里可能出了问题,但看看这个,看看是否有什么突出的地方你可能忽略了:

http://davidwalsh.name/download-urls-content-php-curl