溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

php如何實現(xiàn)保存下載文件

發(fā)布時間:2021-07-14 09:54:03 來源:億速云 閱讀:282 作者:chen 欄目:編程語言

這篇文章主要介紹“php如何實現(xiàn)保存下載文件”,在日常操作中,相信很多人在php如何實現(xiàn)保存下載文件問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”php如何實現(xiàn)保存下載文件”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

php實現(xiàn)保存下載文件的方法:1、通過“function downfile(){...}”方法實現(xiàn)下載文件;2、通過header函數(shù)實現(xiàn)保存下載。

本文操作環(huán)境:windows7系統(tǒng)、PHP7.1版,DELL G3電腦

php 下載保存文件保存到本地的兩種實現(xiàn)方法

這里的下載,指的是 彈出下載提示框。

第一種:

<?php 
function downfile()
{
 $filename=realpath("resume.html"); //文件名
 $date=date("Ymd-H:i:m");
 Header( "Content-type:  application/octet-stream "); 
 Header( "Accept-Ranges:  bytes "); 
Header( "Accept-Length: " .filesize($filename));
 header( "Content-Disposition:  attachment;  filename= {$date}.doc"); 
 echo file_get_contents($filename);
 readfile($filename); 
}
downfile();
?>

或 (推薦這種方法,親測可行,其他的沒測試)

<?php 
function downfile($fileurl)
{
 ob_start(); 
 $filename=$fileurl;
 $date=date("Ymd-H:i:m");
 $size=readfile($filename);
 header( "Content-type:  application/octet-stream "); 
 header( "Accept-Ranges:  bytes "); 
 header( "Content-Disposition:  attachment;  filename= {$date}.doc"); 
 header( "Accept-Length: " .$size);
}
 $url="url地址";
 downfile($url);
?>

第二種:

<?php 
function downfile($fileurl)
{
$filename=$fileurl;
$file  =  fopen($filename, "rb"); 
Header( "Content-type:  application/octet-stream "); 
Header( "Accept-Ranges:  bytes "); 
Header( "Content-Disposition:  attachment;  filename= 4.doc"); 
$contents = "";
while (!feof($file)) {
 $contents .= fread($file, 8192);
}
echo $contents;
fclose($file); 
}
$url="url地址";
downfile($url);
?>

PHP實現(xiàn)下載文件的兩種方法。分享下,有用到的朋友看看哦。

方法一:

<?php
/**
* 下載文件
* header函數(shù)
*
*/
header('Content-Description: File Transfer');
 
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($filepath));
header('Content-Transfer-Encoding: binary');
header('Expires: 0′);
header('Cache-Control: must-revalidate, post-check=0, pre-check=0′);
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
readfile($file_path);
?>

了解php中header函數(shù)的用法。

方法二:

<?php
//文件下載
//readfile
$fileinfo = pathinfo($filename);
header('Content-type: application/x-'.$fileinfo['extension']);
header('Content-Disposition: attachment; filename='.$fileinfo['basename']);
header('Content-Length: '.filesize($filename));
readfile($thefile);
exit();
?>

到此,關(guān)于“php如何實現(xiàn)保存下載文件”的學習就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI