簡體   English   中英

需要php腳本在遠程服務器上下載文件並在本地保存

[英]Need php script to download a file on a remote server and save locally

嘗試在遠程服務器上下載文件並將其保存到本地子目錄。

以下代碼似乎適用於小文件,<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);

?>

有關如何不間斷下載較大文件的任何建議?

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

從PHP 5.1.0開始,file_put_contents()支持通過將stream-handle作為$ data參數傳遞來逐個編寫:

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

file_get_contents不應該用於大二進制文件,因為你可以很容易地達到PHP的內存限制。 我會通過告訴它URL和所需的輸出文件名來exec() wget

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

如果您不知道要下載的文件的格式,請使用此解決方案。

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

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

它有progress_bar和簡單的文件名解析器......

一個更好更輕的腳本是流文件:

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

?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM