需要php脚本在远程服务器上下载文件并在本地保存

big*_*rry 18 php download

尝试在远程服务器上下载文件并将其保存到本地子目录.

以下代码似乎适用于小文件,<1MB,但较大的文件只是超时,甚至没有开始下载.

<?php

 $source = "http://someurl.com/afile.zip";
 $destination = "/asubfolder/afile.zip";

 $data = file_get_contents($source);
 $file = fopen($destination, "w+");
 fputs($file, $data);
 fclose($file);

?>
Run Code Online (Sandbox Code Playgroud)

有关如何不间断下载较大文件的任何建议?

Par*_*ney 32

$ch = curl_init();
$source = "http://someurl.com/afile.zip";
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec ($ch);
curl_close ($ch);

$destination = "/asubfolder/afile.zip";
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);
Run Code Online (Sandbox Code Playgroud)


Bla*_*iev 5

file_get_contents不应该用于大二进制文件,因为你可以很容易地达到PHP的内存限制.我会exec() wget告诉它URL和所需的输出文件名:

exec("wget $url -O $filename");
Run Code Online (Sandbox Code Playgroud)


小智 5

从PHP 5.1.0开始,file_put_contents()支持通过将流句柄作为$ data参数传递来逐段编写:

file_put_contents("Tmpfile.zip", fopen("http://someurl/file.zip", 'r'));
Run Code Online (Sandbox Code Playgroud)