Home > Article > Backend Development > How to modify the file name when downloading in php
php method to modify the file name when downloading: first set the download address; then control the output name in the Controller, code such as "$file = './path/1.zip'...header( 'Pragma: public');readfile($file)...".
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
php changes the file name when downloading the file
Download address:
/download.php?controller=down_file&file=1.zip
Then control the output name in the Controller to achieve
$file = './路径/1.zip'; filename = '2.zip'; header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header("Content-type:text/html;charset=utf-8"); header('Content-Disposition: attachment; filename='. $filename); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); readfile($file); exit;
[Recommended learning: "PHP Video Tutorial" 】
==============
<?php $file_name="aa.rar";//需要下载的文件 $file_name=iconv("utf-8","gb2312","$file_name"); $fp=fopen($file_name,"r+");//下载文件必须先要将文件打开,写入内存 if(!file_exists($file_name)){//判断文件是否存在 echo "文件不存在"; //如果不存在 exit(); //直接退出 } //如果存在,继续执行下载 $file_size=filesize("aa.rar");//判断文件大小 //返回的文件 Header("Content-type: application/octet-stream"); //按照字节格式返回 Header("Accept-Ranges: bytes"); //返回文件大小 Header("Accept-Length: ".$file_size); //弹出客户端对话框,对应的文件名 Header("Content-Disposition: attachment; filename=".$file_name); //防止服务器瞬时压力增大,分段读取 $buffer=1024; while(!feof($fp)){ $file_data=fread($fp,$buffer); echo $file_data; } //关闭文件 fclose($fp); ?>
==========
We generally implement downloading by calling URL to download, but you cannot use this method when you encounter files that IE can recognize when opening, such as downloading a picture, HTML web page, etc. At this time, programming is required to implement it. The following PHP code can solve the problem:
<? if( empty($_GET['FileName'])|| empty($_GET['FileDir'])|| empty($_GET['FileId'])){ echo'<script> alert("非法连接 !"); location.replace ("index.php") </script>'; exit(); } $file_name=$_GET['FileName']; $file_dir=$_GET['FileDir']; $FileId=$_GET['FileId']; $file_dir = $file_dir."/"; if (!file_exists($file_dir.$file_name)) { //检查文件是否存在 echo "文件找不到"; exit; } else { $file = fopen($file_dir . $file_name,"r"); // 打开文件 // 输入文件标签 Header("Content-type: application/octet-stream"); Header("Accept-Ranges: bytes"); Header("Accept-Length: ".filesize($file_dir . $file_name)); Header("Content-Disposition: attachment; filename=" . $file_name); // 输出文件内容 echo fread($file,filesize($file_dir . $file_name)); fclose($file); exit(); } ?>
The above is the detailed content of How to modify the file name when downloading in php. For more information, please follow other related articles on the PHP Chinese website!