Home > Backend Development > PHP Tutorial > PHP file upload, download and delete examples

PHP file upload, download and delete examples

高洛峰
Release: 2023-03-04 16:28:01
Original
1402 people have browsed it

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.重设响应类型
$info = getimagesize($rootPath.$file);
header("Content-Type:".$info['mime']);
//2.执行下载的文件名
header("Content-Disposition:attachment;filename=".$file);
//3.指定文件大小
header("Content-Length:".filesize($rootPath.$file));
//4.响应内容
readfile($rootPath.$file);
Copy after login

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:

PHP file upload, download and delete examples

File The interface for uploading, downloading and deleting, the code is as follows:
html+php embedded:

<!-- 选择上传文件区域-->
<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=&#39;hidden&#39; name=&#39;MAX_FILE_SIZE&#39; value=&#39;100000000&#39;> <!--表单上传文件的大小限制<100M,也可以设置其它值-->
      <input type="file" id="upfile" name="file" />
    </div>
    <input type="submit" value="上传" class="upload" />
  </form>
</div>
<!-- 选择上传文件区域结束-->
 
<!-- 上传文件显示区域-->
<div id="show-file">
  <ul id="ul-list">
    <!-- 内嵌php代码,为了动态显示上传的文件-->
    <?php
    //1.打开目录
    $dir = opendir(&#39;upload&#39;);
    //2.遍历目录
    $i = 0;
    while($file = readdir($dir))
    {
      if($file == &#39;.&#39;||$file == &#39;..&#39;)
        continue;
      echo "<li><img  src=&#39;upload/{$file}&#39;    style="max-width:90%"PHP file upload, download and delete examples" >
        <div><a href=&#39;deleteFile.php?name={$file}&#39;>删除</a></span></div>
        <span><a href=&#39;download.php?name={$file}&#39;>下载</a></span></li>";
    }
    //3.关闭目录
    closedir($dir);
    ?>
    <!-- 内嵌php代码结束-->
  </ul>
</div>
<!-- 上传文件显示区域结束-->
Copy after login

css code:

*{margin:0;padding:0;}
    ul,li{list-style: none;}
    /*最外层的div,目的是包住选择文件按钮,显示框和上传文件按钮*/
    #div1{width:405px;height:38px;position: relative;margin:40px auto;}
 
    /*第二层div包住显示框和上传按钮,右浮动*/
    #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;}
 
    /*鼠标停留在选择文件按钮上的时候切换图片*/
    #div3:hover{background: url("upload.jpg") no-repeat 0 -40px;}
 
    /*显示图片的div->ul,采用左浮动的方式,一行行的排列图片*/
    #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标签的自带样式去掉,鼠标停留时字体换颜色*/
    #show-file ul li span,div a{text-decoration: none;color:orangered;}
    #show-file ul li span,div a:hover{color: #00fa00;}
Copy after login

js code:

<script src="move.js"></script>
 <script>
   window.onload = function ()
   {
     //当选择文件后,会触发这个事件
     $(&#39;upfile&#39;).onchange = function ()
     {
       $(&#39;show&#39;).value = this.value;//把获取到的文件伪路径传到编辑框
     };
     //显示下载按钮
     var aLi = $(&#39;ul-list&#39;).getElementsByTagName(&#39;li&#39;);   //图片
     var aSpan = $(&#39;ul-list&#39;).getElementsByTagName(&#39;span&#39;); //下载按钮
     var aDiv = $(&#39;ul-list&#39;).getElementsByTagName(&#39;div&#39;);  //删除按钮
     for(var i = 0;i<aLi.length;i++)
     {
       aLi[i].index = i;
       aLi[i].onmousemove = function ()
       {
         aSpan[this.index].style.display = &#39;block&#39;;
         aDiv[this.index].style.display = &#39;block&#39;;
         startMove(aDiv[this.index],{opacity:100}); //缓冲运动
         startMove(aSpan[this.index],{opacity:100}); //缓冲运动
       };
       aLi[i].onmouseout = function ()
       {
         aSpan[this.index].style.display = &#39;none&#39;;
         aDiv[this.index].style.display = &#39;none&#39;;
         startMove(aDiv[this.index],{opacity:0});  //缓冲运动
         startMove(aSpan[this.index],{opacity:0});  //缓冲运动
       }
     }
   };
   function $(id)
   {
     return document.getElementById(id);
   }
 </script>
Copy after login

php for processing uploaded files File:

include(&#39;myFunctions.php&#39;);
if(uploadFile(&#39;file&#39;,&#39;upload&#39;))
  header("Location:upFileAndDownFile.php");//会马上跳转回原页面,根本感觉不到页面有跳转到这里
Copy after login

PHP file for processing downloaded files:

include(&#39;myFunctions.php&#39;);
//获取要下载的文件名(加上路径)
$file = $_GET[&#39;name&#39;];
$rootPath = &#39;upload/&#39;;
downLoadFile($file,$rootPath);
 
处理删除文件的php文件:
 
$fileName = &#39;upload/&#39;.$_GET[&#39;name&#39;];
unlink($fileName);
header("Location:upFileAndDownFile.php");
 
其中move.js在前面的JS完美运动框架文章有讲过。 
myFunctions.php中的函数如下:
 
/**
 * @function 下载文件
 * @param $file 要下载的文件名
 * @param $rootPath 文件根路径
 * @return 无
 */
function downLoadFile($file,$rootPath)
{
  //1.重设响应类型
  $info = getimagesize($rootPath.$file);
  header("Content-Type:".$info[&#39;mime&#39;]);
  //2.执行下载的文件名
  header("Content-Disposition:attachment;filename=".$file);
  //3.指定文件大小
  header("Content-Length:".filesize($rootPath.$file));
  //4.响应内容
  readfile($rootPath.$file);
}
 
 
/**
 * @function 上传文件
 * @param $name 表单名 <input type="file" name="pic" />
 * @param $path 上传后,文件存放的路径
 * @return 返回新的文件路径表示上传成功 false 失败
 */
function uploadFile($name,$path)
{
  $file = $_FILES[$name];
  //1.过滤上传文件的错误号
  if($file[&#39;error&#39;] > 0)
  {
    //获取错误信息
    switch($file[&#39;error&#39;])
    {
      case 1:
        $info = &#39;上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。&#39;;
        break;
      case 2:
        $info = &#39;上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。&#39;;
        break;
      case 3:
        $info = &#39;文件只有部分被上传。&#39;;
        break;
      case 4:
        $info = &#39;没有文件被上传。&#39;;
        break;
      case 6:
        $info = &#39;找不到临时文件夹&#39;;
        break;
      case 7:
        $info = &#39;文件写入失败。 &#39;;
        break;
    }
    die("上传错误,原因: ".$info);
  }
  //2.上传文件大小的过滤
  if($file[&#39;size&#39;] > 100000000)  //字节为单位
    die(&#39;上传文件大小超出限制!&#39;);
  //3.上传后的文件名定义
  $newfile = null;
  $fileinfo = pathinfo($file[&#39;name&#39;]); //解析上传文件名
  do{
    $newfile = date(&#39;YmdHis&#39;).".".$fileinfo[&#39;extension&#39;];
  }while(file_exists($path.&#39;/&#39;.$newfile));
  //4.执行文件上传
  //判断是否是一个上传文件
  if(is_uploaded_file($file[&#39;tmp_name&#39;]))
  {
    //执行文件上传(移动文件到指定目录)
    if(move_uploaded_file($file[&#39;tmp_name&#39;],$path.&#39;/&#39;.$newfile))
      return $path.&#39;/&#39;.$newfile;
    else
      return false;
  }
  else
    die(&#39;不是一个上传文件!&#39;);
}
Copy after login

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!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template