Home  >  Article  >  Backend Development  >  How to modify the file name when downloading in php

How to modify the file name when downloading in php

藏色散人
藏色散人Original
2021-02-25 10:23:482137browse

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)...".

How to modify the file name when downloading in php

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" 】

==============

==========

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:

 alert("非法连接 !"); location.replace ("index.php") '; 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn