首頁  >  文章  >  後端開發  >  php實作檔案下載的程式碼

php實作檔案下載的程式碼

WBOY
WBOY原創
2016-07-25 09:00:26926瀏覽
php代码实现文件的下载,主要是header函数的应用,有需要的朋友,可以参考下。

完整代码如下:

<!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>
以上的代码主要是应用php header函数实现文件的下载,在php中有很多的文件内容类型可以这样操作,大家有空多研究下了。


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn