Have you learned how PHP uploads files and downloads them?

Posted by 990805 on Mon, 18 Nov 2019 03:16:40 +0100

Chapter 1 File Upload

1.1 Client Upload Settings

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

Common web sites that support file upload:

Various disks

Portrait

Web Albums

Real-name authentication

Mail Attachments

Simply put, Web development requires users to pass files to the server in the PHP upload category.The server side can only accept copies unless it does not do this.Just like 10086 Customer Service, it accepts when you just call it. It can only accept when the server is busy.

Fundamentals of file upload in PHP:

1) Client form Settings

2) Server handles uploaded files

Form form items that must be set:

<html>
    <head><title>File Upload</title></head>
    <body>
        <form action="./upload.php"  method="post" enctype="multipart/form-data"><!--Must write-->
            <!--typle write file Type, name Must write, name is free-->
            //Select file: <input type="file" name="myfile">
            <input type="submit" value="Upload Files">
        </form>
    </body>
</html>

Notice several characteristic attributes:

1. The file must be uploaded by post, not by get.

2. Entype="multipart/form-data" must be written in the form.

3. The input form must write a name name.

1.2 Processing uploads through PHP on the server side

Receiving and processing uploaded files is handled through PHP scripts, which need three aspects of information:

1) Set up the instructions in the PH profile: for fine tuning the file upload function of PHP.

2)$FILES Multidimensional Array: used to store various information related to uploaded files, other data is obtained using $_POST.

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

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

Instruction Name Default value Functional Description
file_uploads ON Whether to turn on file upload
upload_max_filesize 2M Limit the maximum upload file size for PHP processing, which must be less than post_max_size
post_max_size 8M Limits the maximum amount of information that can be accepted through the POST method, that is, the submission value for the entire POST request.This value must be greater than upload_max_filesize
upload_tmp_dir NULL The temporary path where the uploaded file is stored, which can be an absolute path.The default NULL uses the system's temporary directory.
max_file_uploads 20 Number of files allowed to be uploaded simultaneously

2) $_FILES multidimensional array.

Super Global Array $_FILES

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

    2. $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's bytes.

    4. $_FILES["myfile"]["tmp_name"] has a temporary full path stored on the server after the file has been uploaded. 

    5. $_FILES["myfile"]["error"] value is: file upload error code - php 4.2 added after the function.

Error code for error file upload:

UPLOAD_ERR_OK
 The value is 0, no errors occurred, and the file was uploaded successfully.

UPLOAD_ERR_INI_SIZE
 The value is 1, and the uploaded file exceeds the upload_max_filesize option limit 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
 With a value of 3, only part of the file is uploaded.

UPLOAD_ERR_NO_FILE
 It has a value of 4 and no files have been uploaded.

UPLOAD_ERR_NO_TMP_DIR
 With a value of 6, the temporary folder could not be found.Introduction of PHP 4.3.10 and PHP 5.0.3.

UPLOAD_ERR_CANT_WRITE
 With a value of 7, the file failed to write.Introduction of PHP 5.1.0.

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

Common Data Formats (MIME)

file type MIME Type
Picture File image/gif,image/jpg,image/jpeg,image/png,image/x-png
Plain text and HTML text/txt,text/plain,text/html
Binary file application/octet-stream
Audio format audio/basic
Video format video/mpeg

3) File upload handler for PHP

Successful uploads are placed in a server-side temporary directory, where the file name is a randomly generated temporary file name.

Note: This file will be deleted automatically after the program is executed.You can act like a local file before deleting it.

File Upload Processing Function:

is_uploaded_file - Determines if the file was uploaded through HTTP POST.

Format: bool is_uploaded_file (string $filename)

move_uploaded_file - Moves the uploaded file to a new location.

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

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

Parameter description: File temporary directory, location directory to move to

Case:

1) Set up front-end upload interface

<!DOCTYPE html>
<html lang="en">
<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="upload">
    </form>
</body>
</html>

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

    //Professional handling tools
    //move_uploaded_file()
    //Parameter 1: File Temporary Directory Parameter 2: Location to move to

    //is_uploaded_file() to determine if the file was submitted by http post
    //Parameter 1: File Temporary Directory
    


    //1. Our saved paths are created by time
    //var_dump($_GET);

    //1.1 Saved Path
    $dir='./biran/'.date('Y/m/d/');
    //echo $dir;exit;

    //1.2 Determine if the path to file upload exists or is created if it does not exist
    if(!file_exists($dir)){
        mkdir($dir,777,true);
    }

    //2. Have a good filename and a unique filename
    //2.1 Get the suffix name of the file
    //2.jpg  jpg 
    $suffix = pathinfo($_FILES['pic']['name'],PATHINFO_EXTENSION);
    //echo $suffix;

    //2.2 Rename
    $filename = date('Ymd').uniqid().mt_rand(0,9999).'.'.$suffix;
    //echo $filename;

    //Start handling
    //Determine whether it is a file passed by http post
    if(!is_uploaded_file($_FILES['pic']['tmp_name'])){
        //Not http post upload file
        echo 'Don't be useless!!';exit;
    }

    //Start a real move
    if(move_uploaded_file($_FILES['pic']['tmp_name'],$dir.$filename)){
        echo '11111111111';
    }else{
        echo '22222222222';
    }

Encapsulate as a function:

Ideas:

    function upload(){
        //1. Determine file upload errors

        //2. Determine if the type of file you upload is what you want
        
        //3. Names
        
        //4. Determine if the save path exists
        
        //5. Determine if it is an http post upload
        
        //6. Move pictures
        
        //7. Return the picture name of the successful move
    }

Start encapsulating functions: New function.php

<?php
    /*
        File Upload Function
        @param  string  $name  name value of file upload file field
        @param  string  $dir   File Save Path
        @param  array   $allow Types of files allowed to upload
        return  string  $filename Filename returns false if it fails
     */

    function upload($name,$dir='./upload/',$allow=array('jpg','gif','jpeg','png')){
        //echo $name;exit;
        //var_dump($_FILES);exit;
        //1. Determine file upload errors
        if($_FILES[$name]['error']>0){
            //echo'upload error';
            switch($_FILES[$name]['error']){
                case 1:
                    echo 'More files uploaded than php.ini in upload_max_filesize Value of Option Limit.';
                    break;
                case 2:
                    echo 'The size of the uploaded file exceeds HTML In Form MAX_FILE_SIZE Value specified by option';
                    break;
                case 3:
                    echo 'Only part of the file was uploaded.';
                    break;
                case 4:
                    echo 'No files uploaded.';
                    break;
                case 6:
                    echo 'Temporary folder not found.';
                    break;
                case 7:
                    echo 'File Write Failure.';
                    break;
            }
            return false;
        }

        //2. Determine if the type of file you upload is what you want
        //2.1 Types of uploads allowed
        
        //2.2 Get the suffix name
        $suffix = pathinfo($_FILES[$name]['name'],PATHINFO_EXTENSION);
        //echo $suffix;exit;
        //2.3 Determine if we are allowed to upload
        //var_dump(in_array($suffix,$allow));exit;
        if(!in_array($suffix,$allow)){
            //Type of upload not allowed
            echo  'Big Brother Your upload type doesn't match';
            return false;
        }
        //3. Names
        $filename = date('Ymd').uniqid().mt_rand(0,9999).'.'.$suffix;
        //echo $filename;exit;
        
        //4. Determine if the save path exists
        //4.1 Get Saved Path
        
        //4.2 Handles save paths and slashes behind
        $save_path = rtrim($dir,'/');
        $save_path .='/';
    
        //4.3 Time Folder Processing in Save Path
        $save_path .=date('Y/m/d/');
    
        //4.4 Determine if a saved path exists
        if(!file_exists($save_path)){
            mkdir($save_path,777,true);
        }
    
        //4.5 Stitch together a complete saved path
        $path = $save_path.$filename;
        //echo $path;exit;

        
        //5. Determine if upload is httppost
        if(!is_uploaded_file($_FILES[$name]['tmp_name'])){
            echo 'Rats, screw you!';
            return false;
        }
        
        //6. Move pictures
        if(!move_uploaded_file($_FILES[$name]['tmp_name'],$path)){
            echo 'Move failed';
            return false;
        }
        
        //7. Return the picture name of the successful move
        return $filename;

    }

Call function to start uploading:

<?php
    include './function.php';
    //var_dump($_FILES);exit;

    echo upload('file','./leiding',array('jpg','png'));

Chapter 2 Multi-file Upload

2.1 Multi-file upload with different name

When you need to upload more than one file, there are two 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) 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 not recognized by browsers, they can be downloaded directly using a connection.

    <!-- Because their three browsers don't recognize this type -->
    <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) If the browser does not recognize it, you can use the readfile function.

    <!-- Browsers recognize this type,Will be resolved -->
    <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>
//Receive the name value.
$name = $_GET['name'];

//Implement download capability
//Force browser to pop up Save As dialog
header('content-Disposition:attachment;filename="'.$name.'"');

//At this point, only an empty file is downloaded, you need to read through all the contents with readfile. You can download it.
$path = './downlist/'.$name;
readfile($path);

Topics: PHP Web Development less