Home > Backend Development > PHP Tutorial > php download function

php download function

不言
Release: 2023-03-24 10:48:02
Original
2491 people have browsed it

This is the beginning of the code of the xx.php file

<?php
	//文件下载的封装(超链接的方式)
function down_file($filename,$allowDownExt=array(&#39;zip&#39;,&#39;html&#39;,&#39;rar&#39;)){
	if(!is_file($filename)||!is_readable($filename)){
		return false;
	}
	$ext=strtolower(pathinfo($filename,PATHINFO_EXTENSION));
	if(!in_array($ext, $allowDownExt)){
		return false;
	}
	//发送请求头,告诉浏览器输出的是字节流
	header(&#39;content-type:application/octet-stream&#39;);
	//告诉浏览器文件是按照字节来计算的
	header(&#39;Accept-Ranges:bytes&#39;);
	//告诉浏览器文件的大小
	header(&#39;Accept-Length:&#39;.filesize($filename));
	//告诉浏览器文件是按附件处理,并且告诉浏览器下载的文件的名称
	header(&#39;Content-Disposition:attachment;filename=&#39;.basename($filename));
	//读取文件的内容
	readfile($filename);
	exit;
}
?>
Copy after login

This is the end of the code of the xx.php file

This is the beginning of the code of the index.html file

<!DOCTYPE html>
<html>
<head>
 <meta charset="UTF-8">
 <title>Document</title>
</head>
<body>
 <a href="http://localhost:8081/download.php?filename=5.html">下载5.html</a>
</body>
</html>
Copy after login

This is the end of the code of the index.html file

This is the beginning of the code of the download.php file

<?php
	require_once(&#39;xx.php&#39;);
	$filename=$_GET[&#39;filename&#39;];
	down_file($filename);
?>
Copy after login

This is download. The code of the php file ends

Related recommendations:

PHP printing problem

The above is the detailed content of php download function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template