PHP實現檔案上傳與下載
阿新 • • 發佈:2020-08-30
本文例項為大家分享了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); ?>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。