嗯,这个看起来很简单,而且确实如此。你要做的就是下载一个文件到你的服务器上。
file_put_contents("Tmpfile.zip", file_get_contents("http://someurl/file.zip"));
只是有一个问题。如果你有一个大的文件,比如100MB。那么,你就会耗尽内存,无法下载文件。
我想要的是一种方法,在我下载文件时将其写入磁盘。这样,我就可以下载更大的文件,而不会遇到内存问题。
自 PHP 5.1.0 起,file_put_contents()
支持通过传递一个流句柄作为$data
参数来逐件写入。
file_put_contents("Tmpfile.zip", fopen("http://someurl/file.zip", 'r'));
来自手册。
如果data[即第二个参数]是一个流资源,该流的剩余缓冲区将被复制到指定的文件。这与使用 [
stream_copy_to_stream()
](http://php.net/stream_copy_to_stream)。
(感谢Hakre。)
private function downloadFile($url, $path)
{
$newfname = $path;
$file = fopen ($url, 'rb');
if ($file) {
$newf = fopen ($newfname, 'wb');
if ($newf) {
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
}
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
}
尝试使用cURL
set_time_limit(0); // unlimited max execution time
$options = array(
CURLOPT_FILE => '/path/to/download/the/file/to.zip',
CURLOPT_TIMEOUT => 28800, // set this to 8 hours so we dont timeout on big files
CURLOPT_URL => 'http://remoteserver.com/path/to/big/file.zip',
);
$ch = curl_init();
curl_setopt_array($ch, $options);
curl_exec($ch);
curl_close($ch);
我不确定,但我相信如果使用CURLOPT_FILE
选项,它就会在拉取数据时写入,即不缓冲。