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

需要php脚本在远程服务器上下载文件并在本地保存,php,download,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, $d

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

下面的代码似乎适用于小于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);

?>


关于如何不中断地下载更大的文件,有什么建议吗?

文件获取内容不应该用于大的二进制文件,因为您很容易达到PHP的内存限制。我会告诉它URL和所需的输出文件名,从而
exec()
wget

$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);
exec("wget $url -O $filename");

我总是使用这个代码,它工作得很好

<?php
define('BUFSIZ', 4095);
$url = 'Type The URL Of The File';
$rfile = fopen($url, 'r');
$lfile = fopen(basename($url), 'w');
while(!feof($rfile))
fwrite($lfile, fread($rfile, BUFSIZ), BUFSIZ);
fclose($rfile);
fclose($lfile);
?>     

尝试phpRFT:


它有进度条和简单的文件名deactor…

如果您不知道要下载的文件的格式,请使用此解决方案

$url = 'http:://www.sth.com/some_name.format' ;
$parse_url = parse_url($url) ;
$path_info = pathinfo($parse_url['path']) ;
$file_extension = $path_info['extension'] ;
$save_path = 'any/local/path/' ;
$file_name = 'name' . "." . $file_extension ;
file_put_contents($save_path . $file_name , fopen($url, 'r'))

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

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

一个更好、更轻的脚本,它是流式文件:

<?php

$url  = 'http://example.com/file.zip'; //Source absolute URL
$path = 'file.zip'; //Patch & file name to save in destination (currently beside of PHP script file)

$fp = fopen($path, 'w');

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);

$data = curl_exec($ch);

curl_close($ch);
fclose($fp);

?>


谢谢您的回复。我没有托管脚本的系统上的curl。谢谢。我现在正在尝试,但浏览器似乎挂起。@Biglarir您必须等待文件下载,浏览器可能会挂起,直到下载完成。尝试使用一个中等大小的文件,该文件可以更快地完成,但足够大,可以达到时间限制。对于较大的文件,请使用下面这个更好的单行解决方案:当我运行此程序时,我会显示文件,但大小为0KB。其他方法会导致地址错误或502网关问题。有什么想法吗?它在支持SSH的主机上非常有用。如果您想从远程服务器获取一些文件到另一个服务器
wgethttp://public-url-of-the-file
像这样的URL呢?:这是一个很棒的解决方案-工作快速简单-谢谢!下一级回答如果URL是:请检查以下内容: