歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> PHP實現當前頁面點擊下載文件實例代碼

PHP實現當前頁面點擊下載文件實例代碼

日期:2017/3/1 9:06:38   编辑:Linux編程

下面我們為大家帶來一篇PHP實現當前頁面點擊下載文件的實例代碼。效果還可以,現在就分享給大家,也給大家做個參考。一起過來看看吧。

PHP控制器中代碼

public function downFile($path = ''){
        if(!$path) header("Location: /");
        download($path);
    }

download文件下載函數代碼

function download($file_url,$new_name=''){  
        if(!isset($file_url)||trim($file_url)==''){  
            echo '500';  
        }  
        if(!file_exists($file_url)){ //檢查文件是否存在  
            echo '404';  
        } 
        $file_name=basename($file_url);  
        $file_type=explode('.',$file_url);  
        $file_type=$file_type[count($file_type)-1];  
        $file_name=trim($new_name=='')?$file_name:urlencode($new_name);  
        $file_type=fopen($file_url,'r'); //打開文件  
        //輸入文件標簽 
        header("Content-type: application/octet-stream");  
        header("Accept-Ranges: bytes");  
        header("Accept-Length: ".filesize($file_url));  
        header("Content-Disposition: attachment; filename=".$file_name);  
        //輸出文件內容  
        echo fread($file_type,filesize($file_url));  
        fclose($file_type);
}  

html代碼

<iframe id="iframe" src="" ></iframe>
$(function(){
            $('.downLoad').click(function(){
                var path = $(this).attr('path');
                $('#iframe').attr('src',"php文件路徑?path="+path);
            })
        })

把上面的代碼,分別放到你的程序中執行就可以了。

Copyright © Linux教程網 All Rights Reserved