从 URL 下载文件到服务器 [英] Download File to server from URL

查看:44
本文介绍了从 URL 下载文件到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗯,这个看起来很简单,确实如此.将文件下载到服务器所需要做的就是:

Well, this one seems quite simple, and it is. All you have to do to download a file to your server is:

file_put_contents("Tmpfile.zip", file_get_contents("http://someurl/file.zip"));

只有一个问题.如果你有一个大文件,比如 100mb,该怎么办.然后,您将耗尽内存,无法下载文件.

Only there is one problem. What if you have a large file, like 100mb. Then, you will run out of memory, and not be able to download the file.

我想要的是一种在下载文件时将文件写入磁盘的方法.这样,我就可以下载更大的文件,而不会遇到内存问题.

What I want is a way to write the file to the disk as I am downloading it. That way, I can download bigger files, without running into memory problems.

推荐答案

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

Since PHP 5.1.0, file_put_contents() supports writing piece-by-piece by passing a stream-handle as the $data parameter:

file_put_contents("Tmpfile.zip", fopen("http://someurl/file.zip", 'r'));

来自手册:

如果 data [即第二个参数] 是流资源,则该流的剩余缓冲区将被复制到指定文件.这与使用类似stream_copy_to_stream().

(感谢 Hakre.)

这篇关于从 URL 下载文件到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆