The general idea of ??php file upload, download and deletion examples is as follows, and the specific content is as follows
1. File upload
1. Create the area for uploading files
div1
2. Create the area to display the file
div2
3. Submit the form and upload the file
4. Server Receive file data
Use $_FILE[name] to receive
5. Process the data to see if there are any errors in the uploaded file
The errors are as follows:
1). The uploaded file exceeds the value limited by the upload_max_filesize option in php.ini
2). The size of the uploaded file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form
3). Only part of the file is uploaded
4). No files were uploaded
5). The temporary folder could not be found
6). File writing failed
6. Move the uploaded files from the temporary folder to the specified Folder storage
Use this move_uploaded_file function
Steps 4, 5, and 6 can be made into a function and called directly.
Note: If the page where the file is uploaded needs to embed php code, the file extension cannot be html, but .php
2. File download
1. The client sends the file name to the server
2. The server receives the file name and then adds the path to the file .
3. Then transfer the file data back to the client
Generally these four steps:
//1.重設(shè)響應(yīng)類型 $info = getimagesize($rootPath.$file); header("Content-Type:".$info['mime']); //2.執(zhí)行下載的文件名 header("Content-Disposition:attachment;filename=".$file); //3.指定文件大小 header("Content-Length:".filesize($rootPath.$file)); //4.響應(yīng)內(nèi)容 readfile($rootPath.$file);
3. File deletion
1. The client sends the file name to the server
2. The server receives the file name and then adds the path to the file.
3. Use the unlink function to perform file deletion operations
Here is a small example of uploading, downloading and deleting images.
The effect is as shown:
File The interface for uploading, downloading and deleting, the code is as follows:
html+php embedded:
<!-- 選擇上傳文件區(qū)域--> <div id="div1"> <form action="upLoadFile.php" method="post" enctype="multipart/form-data"> <div id="div2"><input type="text" id="show" /></div> <div id="div3"> <span class="text">選擇文件</span> <input type='hidden' name='MAX_FILE_SIZE' value='100000000'> <!--表單上傳文件的大小限制<100M,也可以設(shè)置其它值--> <input type="file" id="upfile" name="file" /> </div> <input type="submit" value="上傳" class="upload" /> </form> </div> <!-- 選擇上傳文件區(qū)域結(jié)束--> <!-- 上傳文件顯示區(qū)域--> <div id="show-file"> <ul id="ul-list"> <!-- 內(nèi)嵌php代碼,為了動(dòng)態(tài)顯示上傳的文件--> <?php //1.打開目錄 $dir = opendir('upload'); //2.遍歷目錄 $i = 0; while($file = readdir($dir)) { if($file == '.'||$file == '..') continue; echo "<li><img src="/static/imghw/default1.png" data-src="move.js" class="lazy" src='upload/{$file}' style="max-width:90%"PHP file upload, download and delete examples" > <div><a href='deleteFile.php?name={$file}'>刪除</a></span></div> <span><a href='download.php?name={$file}'>下載</a></span></li>"; } //3.關(guān)閉目錄 closedir($dir); ?> <!-- 內(nèi)嵌php代碼結(jié)束--> </ul> </div> <!-- 上傳文件顯示區(qū)域結(jié)束-->
css code:
*{margin:0;padding:0;} ul,li{list-style: none;} /*最外層的div,目的是包住選擇文件按鈕,顯示框和上傳文件按鈕*/ #div1{width:405px;height:38px;position: relative;margin:40px auto;} /*第二層div包住顯示框和上傳按鈕,右浮動(dòng)*/ #div2{float: right;} #div2 input {width:250px;height: 38px;font-size: 22px;} /*第三層div包住input file*/ #div3{float:left;width:140px;height:38px;position: relative; background: url("upload.jpg") no-repeat 0 0;margin-left: 5px;} #div3 input{position: absolute;width:100%;height: 100%;top:0;left: 0; z-index: 1;opacity:0;} /*圖片(選擇文件按鈕)上的文字*/ .text{display: block;width:140px;height: 38px;position: absolute;top: 0; left:0;text-align: center;line-height: 38px;font-size: 28px; color: orchid;} /*上傳按鈕的位置*/ .upload{width:70px;height: 38px;background: greenyellow;position: absolute;top:0;right: -75px;} /*鼠標(biāo)停留在選擇文件按鈕上的時(shí)候切換圖片*/ #div3:hover{background: url("upload.jpg") no-repeat 0 -40px;} /*顯示圖片的div->ul,采用左浮動(dòng)的方式,一行行的排列圖片*/ #show-file{width:760px;height:445px;position: relative;margin:10px auto;overflow: scroll;} #show-file ul{width:760px;height:445px;position: absolute;top:0;left:0;} #show-file ul li{float: left;width:120px;height: 100px;margin: 3px 0 0 3px;position: relative;} /*刪除按鈕的位置和一些樣式*/ #show-file ul li div{display: none;opacity: 0;width:40px;height: 20px;position: absolute;left: 5px;bottom: 5px; background: gold;color: #d32a0e;z-index: 1;cursor: pointer;text-align: center;line-height: 20px;} /*下載按鈕的位置和一些樣式*/ #show-file ul li span{display: none;opacity: 0;width:40px;height: 20px;position: absolute;right: 5px;bottom: 5px; background: gold;color: #d32a0e;z-index: 1;cursor: pointer;text-align: center;line-height: 20px;} /*把a(bǔ)標(biāo)簽的自帶樣式去掉,鼠標(biāo)停留時(shí)字體換顏色*/ #show-file ul li span,div a{text-decoration: none;color:orangered;} #show-file ul li span,div a:hover{color: #00fa00;}
js code:
<script ></script> <script> window.onload = function () { //當(dāng)選擇文件后,會(huì)觸發(fā)這個(gè)事件 $('upfile').onchange = function () { $('show').value = this.value;//把獲取到的文件偽路徑傳到編輯框 }; //顯示下載按鈕 var aLi = $('ul-list').getElementsByTagName('li'); //圖片 var aSpan = $('ul-list').getElementsByTagName('span'); //下載按鈕 var aDiv = $('ul-list').getElementsByTagName('div'); //刪除按鈕 for(var i = 0;i<aLi.length;i++) { aLi[i].index = i; aLi[i].onmousemove = function () { aSpan[this.index].style.display = 'block'; aDiv[this.index].style.display = 'block'; startMove(aDiv[this.index],{opacity:100}); //緩沖運(yùn)動(dòng) startMove(aSpan[this.index],{opacity:100}); //緩沖運(yùn)動(dòng) }; aLi[i].onmouseout = function () { aSpan[this.index].style.display = 'none'; aDiv[this.index].style.display = 'none'; startMove(aDiv[this.index],{opacity:0}); //緩沖運(yùn)動(dòng) startMove(aSpan[this.index],{opacity:0}); //緩沖運(yùn)動(dòng) } } }; function $(id) { return document.getElementById(id); } </script>
php for processing uploaded files File:
include('myFunctions.php'); if(uploadFile('file','upload')) header("Location:upFileAndDownFile.php");//會(huì)馬上跳轉(zhuǎn)回原頁面,根本感覺不到頁面有跳轉(zhuǎn)到這里
PHP file for processing downloaded files:
include('myFunctions.php'); //獲取要下載的文件名(加上路徑) $file = $_GET['name']; $rootPath = 'upload/'; downLoadFile($file,$rootPath); 處理刪除文件的php文件: $fileName = 'upload/'.$_GET['name']; unlink($fileName); header("Location:upFileAndDownFile.php"); 其中move.js在前面的JS完美運(yùn)動(dòng)框架文章有講過。 myFunctions.php中的函數(shù)如下: /** * @function 下載文件 * @param $file 要下載的文件名 * @param $rootPath 文件根路徑 * @return 無 */ function downLoadFile($file,$rootPath) { //1.重設(shè)響應(yīng)類型 $info = getimagesize($rootPath.$file); header("Content-Type:".$info['mime']); //2.執(zhí)行下載的文件名 header("Content-Disposition:attachment;filename=".$file); //3.指定文件大小 header("Content-Length:".filesize($rootPath.$file)); //4.響應(yīng)內(nèi)容 readfile($rootPath.$file); } /** * @function 上傳文件 * @param $name 表單名 <input type="file" name="pic" /> * @param $path 上傳后,文件存放的路徑 * @return 返回新的文件路徑表示上傳成功 false 失敗 */ function uploadFile($name,$path) { $file = $_FILES[$name]; //1.過濾上傳文件的錯(cuò)誤號(hào) if($file['error'] > 0) { //獲取錯(cuò)誤信息 switch($file['error']) { case 1: $info = '上傳的文件超過了 php.ini 中 upload_max_filesize 選項(xiàng)限制的值。'; break; case 2: $info = '上傳文件的大小超過了 HTML 表單中 MAX_FILE_SIZE 選項(xiàng)指定的值。'; break; case 3: $info = '文件只有部分被上傳。'; break; case 4: $info = '沒有文件被上傳。'; break; case 6: $info = '找不到臨時(shí)文件夾'; break; case 7: $info = '文件寫入失敗。 '; break; } die("上傳錯(cuò)誤,原因: ".$info); } //2.上傳文件大小的過濾 if($file['size'] > 100000000) //字節(jié)為單位 die('上傳文件大小超出限制!'); //3.上傳后的文件名定義 $newfile = null; $fileinfo = pathinfo($file['name']); //解析上傳文件名 do{ $newfile = date('YmdHis').".".$fileinfo['extension']; }while(file_exists($path.'/'.$newfile)); //4.執(zhí)行文件上傳 //判斷是否是一個(gè)上傳文件 if(is_uploaded_file($file['tmp_name'])) { //執(zhí)行文件上傳(移動(dòng)文件到指定目錄) if(move_uploaded_file($file['tmp_name'],$path.'/'.$newfile)) return $path.'/'.$newfile; else return false; } else die('不是一個(gè)上傳文件!'); }
When uploading files, pay attention to setting the size limit of the HTML form, the size limit of the server, and the size limit of the post.
The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.
For more articles related to PHP file upload, download and deletion examples, please pay attention to the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

ToversionaPHP-basedAPIeffectively,useURL-basedversioningforclarityandeaseofrouting,separateversionedcodetoavoidconflicts,deprecateoldversionswithclearcommunication,andconsidercustomheadersonlywhennecessary.StartbyplacingtheversionintheURL(e.g.,/api/v

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

Proceduralandobject-orientedprogramming(OOP)inPHPdiffersignificantlyinstructure,reusability,anddatahandling.1.Proceduralprogrammingusesfunctionsorganizedsequentially,suitableforsmallscripts.2.OOPorganizescodeintoclassesandobjects,modelingreal-worlden

PHPdoesnothaveabuilt-inWeakMapbutoffersWeakReferenceforsimilarfunctionality.1.WeakReferenceallowsholdingreferenceswithoutpreventinggarbagecollection.2.Itisusefulforcaching,eventlisteners,andmetadatawithoutaffectingobjectlifecycles.3.YoucansimulateaWe

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.
