php method to download and modify the file name: first set the download address to "/download.php?controller=down_file&file=1.zip"; then control the output name in the Controller.
Recommended: "PHP Video Tutorial"
phpModify 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;
==============
<?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 downloads by calling the url to download, but this method cannot be used when IE can recognize the opened file, such as downloading a Pictures, html web pages, etc., then programming is required to implement them. 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 download and modify file name in php. For more information, please follow other related articles on the PHP Chinese website!