这个看起来很简单,事实也的确如此。你所要做的就是下载一个文件到你的服务器:
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。然后,您将耗尽内存,无法下载文件。
我想要的是一种将文件写入磁盘的方法,因为我正在下载它。这样,我就可以下载更大的文件,而不会遇到内存问题。
当前回答
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);
}
}
其他回答
set_time_limit(0);
$file = file_get_contents('path of your file');
file_put_contents('file.ext', $file);
有3种方法:
File_get_contents和file_put_contents 旋度 打开外部文件
你可以从这里找到例子。
在目标服务器上创建一个名为“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
exec('wget http://someurl/file.zip');
使用php copy()中的简单方法
copy($source_url, $local_path_with_file_name);
注意:如果目标文件已经存在,它将被覆盖
PHP copy()函数
备注:需要设置目标文件夹的权限为777。 在下载到本地机器时使用此方法。
特别注意:777是基于Unix系统的权限,对owner、group和所有人都具有完全的读/写/执行权限。一般来说,我们将此权限授予那些不太需要在web服务器上对公众隐藏的资产。例如:images文件夹。