search
HomeBackend DevelopmentPHP TutorialHow to upload files and download in PHP

Chapter 1 File Upload

1.1 Client Upload Settings

File upload has become a common function in B/S programs . The purpose is that customers can upload files to the specified directory on the server (Server) through the browser (Browser).

Common websites on the Internet that support file upload:

Various network disks

Avatar

Online photo album

Real-name authentication

Email attachment

To put it simply, Web development requires users to pass files to the server, which all fall into the upload category of PHP. The server can only accept copies unless it does not perform this function. Just like 10086 customer service, as long as you call, it will accept it. If it doesn't accept it, it can only mean that the server is busy.

Basic knowledge of file upload in PHP:

1) Client form setting

2) The server operates and processes the uploaded file

Must be set form form items:

<html>
    <head><title>文件上传</title></head>
    <body>
        <form action="./upload.php"  method="post" enctype="multipart/form-data"><!--必须要写-->
            <!--typle写file类型,name必须要写,名字随便-->
            选择文件:<input type="file" name="myfile">
            <input type="submit" value="上传文件">
        </form>
    </body>
</html>

Pay attention to several characteristic attributes:

1. The file must be uploaded in the post method, and the get method cannot be used.

2. The form must write enctype="multipart/form-data".

3. The name must be written in the input form.

1.2 Processing uploads through PHP on the server side

The reception and processing of uploaded files are handled through PHP scripts. Specifically, the following three aspects of information are required:

1 ) Set the instructions in the PH configuration file: used to finely adjust the file upload function of PHP.

2) $FILES multi-dimensional array: used to store various information related to uploaded files. Other data is still obtained using $_POST.

3) PHP file upload processing function: used for subsequent processing of uploaded files.

1) Options related to file upload in the PHP configuration file.

How to upload files and download in PHP

2) $_FILES multi-dimensional array.

Super global array $_FILES

1. The value in $_FILES["myfile"]["name"] is: the name of the file in the client file system.

2. The value in $FILES["myfile"]["type"] is: the type of file passed by the client.

3. The value in $_FILES["myfile"]["size"] is: the size of the file in bytes.

4. The value in $_FILES["myfile"]["tmp_name"] is: the temporary full path stored on the server after the file is uploaded.

5. The value in $_FILES["myfile"]["error"] is: the error code of file upload - a function added after PHP 4.2.

About error error code for file upload:

UPLOAD_ERR_OK

The value is 0, no error occurs, and the file upload is successful.

UPLOAD_ERR_INI_SIZE

The value is 1, and the uploaded file exceeds the limit of the upload_max_filesize option in php.ini.

UPLOAD_ERR_FORM_SIZE

The value is 2, and the size of the uploaded file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form.

UPLOAD_ERR_PARTIAL

The value is 3, and only part of the file is uploaded.

UPLOAD_ERR_NO_FILE

The value is 4 and no file was uploaded.

UPLOAD_ERR_NO_TMP_DIR

The value is 6 and the temporary folder cannot be found. Introduced in PHP 4.3.10 and PHP 5.0.3.

UPLOAD_ERR_CANT_WRITE

The value is 7, file writing failed. Introduced in PHP 5.1.0.

Note: The above values ​​become PHP constants after PHP 4.3.0.

Common data format (MIME)

How to upload files and download in PHP

##3) PHP file upload processing function

The successfully uploaded file will be placed in the temporary directory on the server side, and the file name is a randomly generated temporary file name.

Note: This file will be automatically deleted after the program is executed. Can be operated like a local file before deleting.

File upload processing function:

is_uploaded_file - Determine whether the file is uploaded through HTTP POST.

Format: bool is_uploaded_file (string $filename)

move_uploaded_file — Move the uploaded file to a new location.

Format: bool move_uploaded_file (string $filename, string $destination)

Note: If the destination file already exists, it will be overwritten.

Parameter description: temporary directory of files, the location directory to be moved to

Case:

1) Set the front-end upload interface

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <form action="doup.php" method="post" enctype="multipart/form-data">
        <input type="file" name="pic">
        <input type="submit" value="上传">
    </form>
</body>
</html>

2) doup. php processes the files uploaded to the temporary directory

  //专业搬运工具
    //move_uploaded_file()
    //参数1: 文件临时目录  参数2: 要移动到的位置
    //is_uploaded_file() 判断文件是否是http post提交过来的
    //参数1: 文件临时目录
    //1.我们保存的路径按照时间来创建
    //var_dump($_GET);
    //1.1保存的路径
    $dir=&#39;./biran/&#39;.date(&#39;Y/m/d/&#39;);
    //echo $dir;exit;
    //1.2 判断文件上传的路径是否存在 如果不存在就创建
    if(!file_exists($dir)){
        mkdir($dir,777,true);
    }
    //2.要有个好的文件名 唯一的文件名
    //2.1获取文件的后缀名
    //2.jpg  jpg 
    $suffix = pathinfo($_FILES[&#39;pic&#39;][&#39;name&#39;],PATHINFO_EXTENSION);
    //echo $suffix;
    //2.2重新起名
    $filename = date(&#39;Ymd&#39;).uniqid().mt_rand(0,9999).&#39;.&#39;.$suffix;
    //echo $filename;
    //开始搬运
    //判断是否是http post 传递的文件
    if(!is_uploaded_file($_FILES[&#39;pic&#39;][&#39;tmp_name&#39;])){
        //不是http post上传文件
        echo &#39;别整没用的!!&#39;;exit;
    }
    //开始真正的搬运
    if(move_uploaded_file($_FILES[&#39;pic&#39;][&#39;tmp_name&#39;],$dir.$filename)){
        echo &#39;11111111111&#39;;
    }else{
        echo &#39;22222222222&#39;;
    }

Encapsulate into a function:

Idea:

  function upload(){
        //1.判断文件上传错误
        //2.判断你文件上传的类型是否是你想要的类型
        //3.起名字
        //4.判断保存路径是否存在
        //5.判断是否是http post方式上传
        //6.移动图片
        //7.返回移动成功的图片名
    }

Start encapsulating the function: create a new function.php

<?php
    /*
        文件上传函数
        @param  string  $name  文件上传文件域的name值
        @param  string  $dir   文件保存路径
        @param  array   $allow 文件允许上传的类型
        return  string  $filename 文件名  如果失败 返回false
     */
    function upload($name,$dir=&#39;./upload/&#39;,$allow=array(&#39;jpg&#39;,&#39;gif&#39;,&#39;jpeg&#39;,&#39;png&#39;)){
        //echo $name;exit;
        //var_dump($_FILES);exit;
        //1.判断文件上传错误
        if($_FILES[$name][&#39;error&#39;]>0){
            //echo &#39;上传错误&#39;;
            switch($_FILES[$name][&#39;error&#39;]){
                case 1:
                    echo &#39;上传的文件超过了 php.ini 中upload_max_filesize 选项限制的值.&#39;;
                    break;
                case 2:
                    echo &#39;上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值&#39;;
                    break;
                case 3:
                    echo &#39;文件只有部分被上传.&#39;;
                    break;
                case 4:
                    echo &#39;没有文件被上传.&#39;;
                    break;
                case 6:
                    echo &#39;找不到临时文件夹.&#39;;
                    break;
                case 7:
                    echo &#39;文件写入失败.&#39;;
                    break;
            }
            return false;
        }
        //2.判断你文件上传的类型是否是你想要的类型
        //2.1允许上传的类型
        //2.2 获取后缀名
        $suffix = pathinfo($_FILES[$name][&#39;name&#39;],PATHINFO_EXTENSION);
        //echo $suffix;exit;
        //2.3 判断是否是我们允许上传的类型
        //var_dump(in_array($suffix,$allow));exit;
        if(!in_array($suffix,$allow)){
            //不允许上传的类型
            echo  &#39;大哥你的上传类型不符合&#39;;
            return false;
        }
        //3.起名字
        $filename = date(&#39;Ymd&#39;).uniqid().mt_rand(0,9999).&#39;.&#39;.$suffix;
        //echo $filename;exit;
        //4.判断保存路径是否存在
        //4.1 得到保存路径
        //4.2 处理保存路径和后面的斜杠
        $save_path = rtrim($dir,&#39;/&#39;);
        $save_path .=&#39;/&#39;;
        //4.3 保存路径中的时间文件夹处理
        $save_path .=date(&#39;Y/m/d/&#39;);
        //4.4 判断保存的路径是否存在
        if(!file_exists($save_path)){
            mkdir($save_path,777,true);
        }
        //4.5 拼接一个完整的保存路径
        $path = $save_path.$filename;
        //echo $path;exit;
        //5.判断是否是httppost方式上传
        if(!is_uploaded_file($_FILES[$name][&#39;tmp_name&#39;])){
            echo &#39;滚蛋!&#39;;
            return false;
        }
        //6.移动图片
        if(!move_uploaded_file($_FILES[$name][&#39;tmp_name&#39;],$path)){
            echo &#39;移动失败&#39;;
            return false;
        }
        //7.返回移动成功的图片名
        return $filename;
    }

Call Function starts uploading:

<?php
    include &#39;./function.php&#39;;
    //var_dump($_FILES);exit;
    echo upload(&#39;file&#39;,&#39;./leiding&#39;,array(&#39;jpg&#39;,&#39;png&#39;));

Chapter 2 Multiple file upload

2.1 Multiple file upload with different names

When multiple files need to be uploaded , there are two implementation solutions:

1) Use different form elements.

<input type="file" name="file_a">
<input type="file" name="file_b">
<input type="file" name="file_c">

2) Use form elements in array format.

<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">

Chapter 3 File Download

1) For files that are not recognized by the browser, you can directly use a connection to download them.

  <!-- 因为他们三个浏览器不认识这样的类型 -->
    <a href="./downlist/1.rar">1.rar</a>
    <a href="./downlist/1.exe">1.exe</a>
    <a href="./downlist/1.avi">1.avi</a>

2) 对于浏览器不识别的,可以利用 readfile 函数。

  <!-- 浏览器认识这样的类型,就会被解析 -->
    <a href="./action.php?name=1.html">1.html</a>
    <a href="./action.php?name=1.php">1.php</a>
    <a href="./action.php?name=1.txt">1.txt</a>
    <a href="./action.php?name=1.jpg">1.jpg</a>
//接收一下name值.
$name = $_GET[&#39;name&#39;];
//实现下载功能
//强制浏览器弹出另存为对话框
header(&#39;content-Disposition:attachment;filename="&#39;.$name.&#39;"&#39;);
//此时只是下载了一个空文件,需要利用readfile读一遍所有的内容.便可下载.
$path = &#39;./downlist/&#39;.$name;
readfile($path);

The above is the detailed content of How to upload files and download in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Laravel routing parameter delivery and controller method definition: Avoiding common errors and best practicesLaravel routing parameter delivery and controller method definition: Avoiding common errors and best practicesJul 23, 2025 pm 07:27 PM

This tutorial details the correct method of parameter passing in Laravel routing, and corrects common errors in writing parameter placeholders into controller method names. The article provides examples of standardized routing definitions and controller methods, and emphasizes that deletion operations should prioritize the use of HTTPDELETE methods to enhance routing semantics and maintainability.

Guide to matching Laravel routing parameter passing and controller methodGuide to matching Laravel routing parameter passing and controller methodJul 23, 2025 pm 07:24 PM

This article aims to resolve common errors in the Laravel framework where routing parameter passing matches controller methods. We will explain in detail why writing parameters directly to the controller method name in the routing definition will result in an error of "the method does not exist", and provide the correct routing definition syntax to ensure that the controller can correctly receive and process routing parameters. In addition, the article will explore best practices for using HTTPDELETE methods in deletion operations.

How to use PHP to develop a Q&A community platform Detailed explanation of PHP interactive community monetization modelHow to use PHP to develop a Q&A community platform Detailed explanation of PHP interactive community monetization modelJul 23, 2025 pm 07:21 PM

1. The first choice for the Laravel MySQL Vue/React combination in the PHP development question and answer community is the first choice for Laravel MySQL Vue/React combination, due to its maturity in the ecosystem and high development efficiency; 2. High performance requires dependence on cache (Redis), database optimization, CDN and asynchronous queues; 3. Security must be done with input filtering, CSRF protection, HTTPS, password encryption and permission control; 4. Money optional advertising, member subscription, rewards, commissions, knowledge payment and other models, the core is to match community tone and user needs.

Efficiently use JSON data to implement cascading drop-down menus in Laravel Blade templatesEfficiently use JSON data to implement cascading drop-down menus in Laravel Blade templatesJul 23, 2025 pm 07:18 PM

This article details how to load a local JSON file in a Laravel application and pass its data to a Blade template. By processing JSON parsing by the controller, the view layer uses Blade's @foreach instruction to traverse the data, thereby realizing dynamically generating drop-down menus. In particular, the article also explores in-depth how to combine JavaScript to implement multi-level linkage drop-down menu functions to provide users with dynamic content display based on selection, and provides practical code examples and precautions for implementing such interactions.

Deep analysis of matching Laravel routing parameter transfer and controller methodDeep analysis of matching Laravel routing parameter transfer and controller methodJul 23, 2025 pm 07:15 PM

This article deeply explores the correct transmission of routing parameters and the matching mechanism of controller methods in the Laravel framework. In response to the common "method does not exist" error caused by writing routing parameters directly to the controller method name, the article elaborates on the correct way to define routing, that is, declare parameters in the URI and receive them as independent parameters in the controller method. At the same time, the article also provides code examples and suggestions on best practices for HTTP methods, aiming to help developers build more robust and RESTful Laravel applications.

PHP integrated AI intelligent image processing PHP image beautification and automatic editingPHP integrated AI intelligent image processing PHP image beautification and automatic editingJul 23, 2025 pm 07:12 PM

PHP integrated AI image processing requires the help of a third-party API or local model, which cannot be directly implemented; 2. Use ready-made services such as Google CloudVision API to quickly realize facial recognition, object detection and other functions. The advantages are fast development and strong functions. The disadvantages are that they need to pay, rely on the network and have data security risks; 3. Deploy local AI models through PHP image library such as Imagick or GD combined with TensorFlowLite or ONNXRuntime. It can be customized, the data is safer, and the cost is low, but the development is difficult and requires AI knowledge; 4. Mixed solutions can combine the advantages of API and local model, such as using API for detection and beautification of local models; 5. Selecting AI image processing API should be comprehensive

Twilio Voice Call Maintenance and Recovery: Meeting Functions and Independent Call Leg Management PracticeTwilio Voice Call Maintenance and Recovery: Meeting Functions and Independent Call Leg Management PracticeJul 23, 2025 pm 07:09 PM

This article discusses in-depth two main strategies for realizing voice call holding (Hold) and recovery (Unhold) on the Twilio platform. First, we introduce the detailed introduction to leveraging the Twilio Conference feature to easily manage call retention by updating the Participant resources, and provide corresponding code examples. Second, for scenarios where more detailed control of independent call legs (CallLeg) is required, how to combine TwiML instructions (such as and/) to handle call reconnection, while highlighting the complexity of this approach. The article aims to provide professional and practical guidance to help developers choose the most suitable implementation solution according to specific needs.

Laravel routing parameter passing: correctly define the controller method and routing bindingLaravel routing parameter passing: correctly define the controller method and routing bindingJul 23, 2025 pm 07:06 PM

This article discusses the correct posture of parameter transfer of controller method in Laravel routing in depth. In response to common errors caused by writing routing parameters directly to the controller method name, the correct routing definition syntax is explained in detail, and the mechanism of Laravel automatic parameter binding is emphasized. At the same time, the article recommends using HTTPDELETE method that is more in line with RESTful specifications to handle deletion operations to improve the maintainability and semantics of the application.

See all articles

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.