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

2022-08-30 21:44:36

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

以下代码似乎适用于小文件,<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);

?>

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


答案 1
$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);

答案 2

file_get_contents不应该用于大型二进制文件,因为您可以轻松达到PHP的内存限制。我会告诉它URL和所需的输出文件名:exec()wget

exec("wget $url -O $filename");

推荐