本文实例为大家分享了PHP实现文件上传与下载的具体代码,供大家参考,具体内容如下
主页index.php
<html> <head> <title>图片操作</title> <style> #contAIns { width: 500px; margin: 0 auto; text-align: center; color: #0F0; } th { background: #ccc; } td { width: 150px; height: 50px; text-align: center; } </style> </head> <body> <div id="contains"> <h2>图片上传和下载</h2> <!----------------文件上传表单-------------> <form action="doupload.php" method="post" enctype="multipart/form-data"> <input type="hidden" value="10000000" /> <!---避免上传后发现文件过大---> <input type="file" name="pic"/> <input type="submit" value="上传"/> </form> <!---------------------------------------> <table width="500" border="0"> <tr> <th>序号</th><th>图片</th><th>添加时间</th><th>操作</th> </tr> <?php //1.打开目录 $dir = opendir("./imgs"); //2.遍历目录 $i = 0; $color = "#ff0"; while ($f = readdir($dir)){ //$f代表这每个文件的名字 if ($f == '.' || $f == "..") continue; //处理特殊隐藏的文件 $i++; if ($i % 2 == 0) $color = "#ccc"; else $color = "#ffa"; echo "<tr bgcolor=$color>"; echo "<td>{$i}</td>"; echo "<td><img src='./imgs/{$f}' width='150' height='50'/></td>"; echo "<td>".date("Y-m-d", filectime('./imgs/'.$f))."</td>"; echo "<td><a href='./imgs/{$f}'>查看</a> <a href='download.php?name={$f}'>下载</a></td>"; echo "</tr>"; // echo $f." "; } ?> </table> </div> </body> </html>
上传doupload.php
<?php
/* echo "<pre>";
var_dump($_FILES);
echo "</pre>";*/
//1.获取上传文件信息
$upfile = $_FILES["pic"];
$path = "./imgs/";
//2、过滤错误信息
if ($upfile["error"] > 0) {
die("上传文件错误");
}
//3、本次上传文件的大小过滤
if ($upfile["size"] > 10000000) {
die("上传文件超出限制");
}
//4、处理文件类型
$typelist = array("jpeg","jpg","png","gif");
$arr = explode(".", basename($upfile['name'])); //以'.'分割字符串为数组
$bz = array_pop($arr); //获取文件的后缀名
if (!in_array($bz, $typelist)) { //如果给定的值 value 存在于数组 array 中则返回 true
die("上传文件类型非法!".$upfile["type"]);
}
//5、设置相同文件的名字不同
$newfile = date("YmdHis").rand(100, 999).".".$bz;
//
if (is_uploaded_file($upfile["tmp_name"])) { //判断文件是否是通过post上传
//执行文件上传
if (move_uploaded_file($upfile["tmp_name"], $path.$newfile)) {//将上传的文件保存在新位置
echo "上传成功!";
echo "<a href='index.php'>浏览</a>";
}else {
die("上传失败");
}
}
?>
下载download.php
<?php
//1.获取于要下载的文件名
$file = "./imgs/".$_GET["name"];
// echo $file;
//2.重设响应类型
$info = getimagesize($file); //获取文件大小
// var_dump($info);
header("Content-Type:".$info["mime"]);
//3.执行下载文件名
header("Content-Disposition:attachment;filename=".$_GET["name"]);
//4.指定文件大小
header("Content-Length:".filesize($file));
//5.响应内容
readfile($file);
?>


