Home > Backend Development > PHP Tutorial > PHP code to implement file download

PHP code to implement file download

WBOY
Release: 2016-07-25 09:00:26
Original
986 people have browsed it
The PHP code implements file downloading, mainly the application of the header function. Friends in need can refer to it.

The complete code is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PHP文件下载_程序员之家_bbs.it-home.org</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
$file_name="test_ftp.zip";
if(!file_exists($file_name)){
echo "文件不存在!";
return;
}
$file_size=filesize($file_name);
$brtype = $_SERVER["HTTP_USER_AGENT"];//获取客户端浏览器信息
//中文文件名需要编码处理
//$encoded_filename = urlencode($filename);
//$encoded_filename = str_replace("+", "%20", $encoded_filename);
//中文文件名,需要编码处理
header("Content-type: application/zip");//指定下载的文件类型为zip格式
header("Accept-Ranges: bytes");
header("Content-Length:".$file_size);
if (preg_match("/MSIE/", $brtype)) {
   header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');//IE下如果处理中文文件名需要编码
} else if (preg_match("/Firefox/", $brtype)) {
   header('Content-Disposition: attachment; filename*="utf8\'\'' . $file_name . '"');
} else {
   header('Content-Disposition: attachment; filename="' . $file_name . '"');
}
$data=readfile($file_name);
echo $data;
?>
</body>
</html>
Copy after login
The above code mainly uses the php header function to download files. There are many file content types in php that can be operated in this way. Please study more when you have time.


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