1. 程式人生 > >php檔案下載並重命名

php檔案下載並重命名

1.下載本地檔案

$file_url = “./本地路徑”
 $out_filename = ‘下載後自動儲存的名字’;
 if(!file_exists($file_url)) {
     echo "不存在";
 }else{
           header('Accept-Ranges: bytes');
           header('Accept-Length: ' . filesize( $file_url ));
           header('Content-Transfer-Encoding: binary');
           header('Content-type: application/octet-stream');
           header('Content-Disposition: attachment; filename=' . $out_filename);
           header('Content-Type: application/octet-stream; name=' . $out_filename);
           if(is_file($file_url) && is_readable($file_url)){
                $file = fopen($file_url, "r");
                 echo fread($file, filesize($file_url));
                 fclose($file);
            }

2.下載遠端檔案

$file_ur = ‘遠端檔案地址’;

$out_filename='下載後自動儲存的檔名';

            $file = @fopen($file_url, "r");
            if($file){
                $content="";
                while(!feof($file)){//測試檔案指標是否到了檔案結束的位置
                    $data=fread($file,1024);
                    $content.=$data;
                }
                fclose($file);
                $filesize = strlen($content);
                header('Accept-Ranges: bytes');
                header('Accept-Length: ' . $filesize);
                header('Content-Transfer-Encoding: binary');
                header('Content-type: application/octet-stream');
                header('Content-Disposition: attachment; filename=' . $out_filename);
                header('Content-Type: application/octet-stream; name=' . $out_filename);
                echo $content;
                die();  
            }else{
                echo "檔案不存在";
            }