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

时间:2010-12-21 21:44:25

标签: 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, $data);
 fclose($file);

?>

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

7 个答案:

答案 0 :(得分:32)

$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);

答案 1 :(得分:5)

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

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

答案 2 :(得分:4)

自PHP 5.1.0起,file_put_contents()支持通过将stream-handle作为$ data参数传递来逐个编写:

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

答案 3 :(得分:1)

我总是使用这个代码,它运行得很好。

<?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);
?>     

答案 4 :(得分:1)

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

/**
 * Calculates the expected QPS given a stableRate, a warmupPeriod, and a saturatedPeriod.
 * <p>
 * Both specified periods must use the same time unit.
 *
 * @param stableRate      how many permits become available per second once stable
 * @param warmupPeriod    the duration of the period where the {@code RateLimiter} ramps up
 *                        its rate, before reaching its stable (maximum) rate
 * @param saturatedPeriod the duration of the period for which the {@code RateLimiter} has
 *                        been under saturated demand starting from a cold state
 * @return The expected QPS assuming saturated demand starting from a cold state
 */
public static double qps(double stableRate, double warmupPeriod, double saturatedPeriod) {
    if (saturatedPeriod >= warmupPeriod) {
        return stableRate;
    }
    double coldRate = stableRate / 3.0;
    return (stableRate - coldRate) * saturatedPeriod / warmupPeriod + coldRate;
}

答案 5 :(得分:0)

试用phpRFT:http://sourceforge.net/projects/phprft/files/latest/download?source=navbar

它有progress_bar和简单的文件名识别器......

答案 6 :(得分:0)

一个更好更轻的脚本,即流文件:

<?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);

?>