这个看起来很简单,事实也的确如此。你所要做的就是下载一个文件到你的服务器:
file_put_contents("Tmpfile.zip", file_get_contents("http://someurl/file.zip"));
只有一个问题。如果你有一个大文件,比如100mb。然后,您将耗尽内存,无法下载文件。
我想要的是一种将文件写入磁盘的方法,因为我正在下载它。这样,我就可以下载更大的文件,而不会遇到内存问题。
这个看起来很简单,事实也的确如此。你所要做的就是下载一个文件到你的服务器:
file_put_contents("Tmpfile.zip", file_get_contents("http://someurl/file.zip"));
只有一个问题。如果你有一个大文件,比如100mb。然后,您将耗尽内存,无法下载文件。
我想要的是一种将文件写入磁盘的方法,因为我正在下载它。这样,我就可以下载更大的文件,而不会遇到内存问题。
当前回答
在目标服务器上创建一个名为“downloads”的文件夹 将[此代码]保存到.php文件中并在目标服务器中运行
下载:
<html>
<form method="post">
<input name="url" size="50" />
<input name="submit" type="submit" />
</form>
<?php
// maximum execution time in seconds
set_time_limit (24 * 60 * 60);
if (!isset($_POST['submit'])) die();
// folder to save downloaded files to. must end with slash
$destination_folder = 'downloads/';
$url = $_POST['url'];
$newfname = $destination_folder . basename($url);
$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);
}
?>
</html>
其他回答
PHP 4和5解决方案:
Readfile()本身不会出现任何内存问题,即使在发送大文件时也是如此。 如果fopen包装器已启用,则URL可以用作此函数的文件名。
http://php.net/manual/en/function.readfile.php
最好的解决方案
在系统&中安装aria2c
echo exec("aria2c \"$url\"")
从PHP 5.1.0开始,file_put_contents()通过传递一个流句柄作为$data参数来支持逐条写入:
file_put_contents("Tmpfile.zip", fopen("http://someurl/file.zip", 'r'));
摘自手册:
如果data[即第二个参数]是流资源,则该流的剩余缓冲区将被复制到指定的文件中。这与使用类似 stream_copy_to_stream()。
(谢谢哈克雷。
简单的解决方案:
<?php
exec('wget http://someurl/file.zip');
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);
}
}