PHP to implement file download with code

Source: Internet
Author: User
Tags exit html page php code

We generally implement the download is to call the URL to download, but encountered IE can identify open files can not be used in this way, such as downloading a picture, HTML page, etc., then need to program to achieve, the following PHP code can be resolved:

<?
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();
}
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.