PHP implementation of File upload, download and delete methods

Source: Internet
Author: User
Tags php file upload readfile
This article mainly for you in detail the php file upload, download and delete examples, with a certain reference value, interested in small partners can refer to

php file upload, download and delete examples of the general idea is as follows, the details are as follows

I. File upload

1. Make the area where the files are uploaded
P1

2. Make the area where the file is displayed
P2

3. Submit the form and upload the file

4. server receives file data
Receive with $_file[name]

5. Process the data to see if there is an error uploading the file

There are several errors:
1). The uploaded file exceeds the value of the Upload_max_filesize option limit 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 are uploaded
5). Unable to find Temp folder
6). File Write Failed

6. Move the uploaded file from the Temp folder to the specified folder for storage
With this move_uploaded_file function
Where 4 5 6 steps can be made into a function called directly.
Note: File upload page If you want to embed PHP code, the file name extension cannot be HTML, but. php

Two. 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 it.

3. Then transfer the file data back to the client

These are generally four steps:

   1. Reset the response type  $info = getimagesize ($rootPath. $file);  Header ("Content-type:". $info [' MIME ']);  2. Execute the downloaded filename  header ("Content-disposition:attachment;filename=". $file);  3. Specify the file size  header ("Content-length:". FileSize ($rootPath. $file));  4. Response Content  ReadFile ($rootPath. $file);

Three. 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 it.

3. Perform a delete file operation with the unlink function

Here is a small example of an image upload and download deletion.
Effect:

File upload to download the deleted interface, the code is as follows:
html+php Embedded:


<!--Select Upload file area--><p id= "P1" > <form action= "uploadfile.php" method= "post" enctype= "Multipart/form-data" > <p id= "p2" ><input type= "text" id= "show"/></p> <p id= "P3" > <span class= "text" &G t; Select File </span> <input type= ' hidden ' name= ' max_file_size ' value= ' 100000000 ' > <!--the size limit of the form upload file <100m, also  Other values can be set--<input type= "file" id= "Upfile" name= "file"/> </p> <input type= "Submit" value= "Upload" class= "Upload"/> </form></p><!--Select Upload file area end--><!--upload file display area--><p id= "Show-file" > &    Lt;ul id= "Ul-list" > <!--embed PHP code in order to dynamically display uploaded files--<?php//1. Open Directory $dir = opendir (' upload ');    2. Traverse directory $i = 0; while ($file = Readdir ($dir)) {if ($file = = '. ' | |        $file = = ' ... ')      Continue echo "<li> <p><a href= ' deletefile.php?name= {$file} ' > Delete &LT;/A&GT;&LT;/SPAN&GT;&LT;/P&GT    <span><a href= ' download.php?name={$file} ' > Download </a></span></li> ';    }//3. Close directory Closedir ($DIR); ?> <!--inline PHP code ends-</ul></p><!--upload file display area ended-

CSS code:


*{margin:0;padding:0;}    Ul,li{list-style:none;}    /* Outermost P, the purpose is to wrap the Select File button, the display box and the Upload file button */#p1 {width:405px;height:38px;position:relative;margin:40px auto;}    /* Second Layer P wrap the Display box and upload button, right float */#p2 {float:right;}    #p2 input {width:250px;height:38px;font-size:22px;}      /* Third layer P wrap input file*/#p3 {float:left;width:140px;height:38px;position:relative;    Background:url ("upload.jpg") no-repeat 0 0;margin-left:5px;}      #p3 input{position:absolute;width:100%;height:100%;top:0;left:0;    z-index:1;opacity:0;}      /* Text on the picture (select File button) */. text{display:block;width:140px;height:38px;position:absolute;top:0;      left:0;text-align:center;line-height:38px;font-size:28px;    Color:orchid;}    /* location of the upload button */. Upload{width:70px;height:38px;background:greenyellow;position:absolute;top:0;right: -75px;}    /* Hover over the Select File button to toggle the picture */#p3: Hover{background:url ("upload.jpg") No-repeat 0-40px;} /* Displays the picture's P->ul, uses the left floating way, the row arranges the picture */#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;} /* Remove the position of the button and some styles */#show-file ul Li P{display:none;opacity:0;width:40px;height:20px;position:absolute;left:5px;botto      m:5px;    Background:gold;color: #d32a0e; z-index:1;cursor:pointer;text-align:center;line-height:20px;} /* Location of the download button and some styling */#show-file ul Li Span{display:none;opacity:0;width:40px;height:20px;position:absolute;right:5px;b      ottom:5px;    Background:gold;color: #d32a0e; z-index:1;cursor:pointer;text-align:center;line-height:20px;}    /* Remove the self-styled style of a label, the font for color */#show-file ul li Span,p a{text-decoration:none;color:orangered;} #show-file ul li Span,p a:hover{color: #00fa00;}

JS Code:

 <script src= "Move.js" ></script> <script> window.onload = function () {//When the file is selected, this event is triggered      $ (' upfile '). onchange = function () {$ (' show '). Value = this.value;//Upload the acquired file pseudo-path to the edit box};   Show Download button var aLi = $ (' ul-list '). getElementsByTagName (' Li '); Picture var Aspan = $ (' ul-list '). getElementsByTagName (' span ');  Download button var ap = $ (' ul-list '). getElementsByTagName (' P ');        Delete button for (var i = 0;i<ali.length;i++) {ali[i].index = i;          Ali[i].onmousemove = function () {aspan[this.index].style.display = ' block ';          Ap[this.index].style.display = ' block '; Startmove (ap[this.index],{opacity:100}); Buffered Motion Startmove (aspan[this.index],{opacity:100});        Buffer movement};          Ali[i].onmouseout = function () {Aspan[this.index].style.display = ' none ';          Ap[this.index].style.display = ' None ';  Startmove (ap[this.index],{opacity:0}); Buffered motion StartMove (aspan[this.index],{opacity:0});    Buffer Movement}};    function $ (ID) {return document.getElementById (ID); } </script>

To process PHP files for uploading files:

Include (' myfunctions.php '), if (UploadFile (' file ', ' upload '))  header ("Location:upFileAndDownFile.php");// Will immediately jump back to the original page, there is no sense that the page has to jump here

PHP files for processing downloaded files:

Include (' myfunctions.php ');//Gets the file name to download (plus the path) $file = $_get[' name '); $rootPath = ' upload/';d ownloadfile ($file, $ RootPath); The php file that handles deleting files: $fileName = ' upload/'. $_get[' name '];unlink ($fileName); header ("Location: Upfileanddownfile.php "), where move.js in front of the JS perfect motion frame article has been talked about. The functions in myfunctions.php are as follows:/** * @function Download file * @param $file file name to download * @param $rootPath file root path * @return No */function downLoad  File ($file, $rootPath) {//1. Reset response Type $info = GetImageSize ($rootPath. $file);  Header ("Content-type:". $info [' MIME ']);  2. Execute the downloaded filename header ("content-disposition:attachment;filename=". $file);  3. Specify the file size header ("Content-length:". FileSize ($rootPath. $file)); 4. Response Content ReadFile ($rootPath. $file);} /** * @function Upload file * @param $name table sole name <input type= "file" name= "pic"/> * @param $path upload the file path * @return return the new file  The path indicates that the upload succeeded false failed */function UploadFile ($name, $path) {$file = $_files[$name]; 1. Filter the error number of the upload file if ($file [' Error '] > 0) {//Get error message switch ($file [' ERROR ']) {Case 1: $info = ' uploaded file Exceeded PHP.INI, the value of the upload_max_filesize option limit.        ';      Break Case 2: $info = ' the size of the uploaded file exceeds the value specified by the Max_file_size option in the HTML form.        ';      Break Case 3: $info = ' file is only partially uploaded.        ';      Break Case 4: $info = ' no files were uploaded.        ';      Break        Case 6: $info = ' temporary folder not found ';      Break Case 7: $info = ' File write failed.        ';    Break  } die ("Upload error, Reason:". $info);  //2. upload file size filter if ($file [' Size '] > 100000000)//Bytes die (' Upload file size exceeds limit! ');  3. The uploaded file name definition $newfile = NULL; $fileinfo = PathInfo ($file [' name ']); Parse the upload file name do{$newfile = Date (' Ymdhis '). ".".  $fileinfo [' extension ']; }while (File_exists ($path. '  /'. $newfile)); 4. Execute File Upload//Determine if it is an upload file if (is_uploaded_file ($file [' tmp_name ')) {//Perform file upload (move file to specified directory) if (Move_uploaded_file ($fil e[' Tmp_name '), $path. ' /'. $newfile)) return $path. '    /'. $newfile;  else return false; } else die (' not an upload file! ');}

When uploading a file note to set the size limit of the HTML form and the size limit of the server, post size limit.

Summary: The above is the entire content of this article, I hope to be able to help you learn.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.