PHP Single File Upload Principle and Upload Function Encapsulation Operation Example

  • 2021-12-19 06:11:46
  • OfStack

This paper describes the principle of PHP single file uploading and the encapsulation operation of uploading function. Share it for your reference, as follows:

Form:

0.php:


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> Untitled document </title>
</head>
<body>
<form action="000.php" method="post" enctype="multipart/form-data">
 Please select the file you want to upload <input type="file" name="myfile"/>
<input type="submit" value=" Upload a file "/>
</form>
</body>
</html>

Encapsulation of single file upload function:

00.php:


<?php
// Encapsulation of single file upload function 
// File upload principle: Upload the client files to the server, and then move the temporary files on the server to the specified directory. 
// Direction of the file: Client-- > Server ( Temporary file ) -- > Specify a directory , When the file enters the server, it is a temporary file , The name of the temporary file will be used in this operation tmp_name . 
// It is not safe to set limits on uploading files (file type and size) on the client side, because the client can modify the limits through source code, so set limits here on the server side. 
// Set the code to UTF-8 To avoid Chinese garbled codes 
header('Content-Type:text/html;charset=utf-8');
// Pass $_FILES Receive the information of uploaded files 
//$fileInfo = $_FILES['myFile'];
function uploadFile($fileInfo,$uploadPath='uploads',$flag=true,$allowExt=array('jpeg','jpg','png','gif'),$maxSize = 2097152){
// Judgment error number , Only for 0 Or is it UPLOAD_ERR_OK, No error occurred, upload succeeded 
    if($fileInfo['error']>0){
        // Attention! Error message does not 5
        switch($fileInfo['error']){
            case 1:
                $mes= ' Upload files exceeded PHP In the configuration file upload_max_filesize The value of the option ';
                break;
            case 2:
                $mes= ' Beyond HTML Form MAX_FILE_SIZE Limit size ';
                break;
            case 3:
                $mes= ' The file part is uploaded ';
                break;
            case 4:
                $mes= ' Upload file not selected ';
                break;
            case 6:
                $mes= ' Temporary directory not found ';
                break;
            case 7:
                $mes= ' File write failure ';
                break;
            case 8:
                $mes= ' The uploaded file is PHP Extension program interrupt ';
                break;
        }
        exit($mes);
        return false;
    }
    $ext=pathinfo($fileInfo['name'],PATHINFO_EXTENSION);
    //$allowExt=array('jpeg','jpg','png','gif');
    // Detect the type of uploaded file 
    if (! in_array ( $ext, $allowExt )) {
        exit ( ' Illegal file type ' );
    }
    // Check whether the size of uploaded text conforms to the specification 
    //$maxSize = 2097152;//2M
    if($fileInfo['size']>$maxSize){
        exit(' The uploaded file is too large ');
    }
    // Detect whether the picture is a real picture type 
    //$flag=true;
    if($flag){
        if(!getimagesize($fileInfo['tmp_name'])){
            exit(' Not a real picture type ');
        }
    }
    // Whether the test is passed HTTP POST Upload it in a way 
    if (! is_uploaded_file ( $fileInfo ['tmp_name'] )) {
        exit ( ' File is not passed through HTTP POST Uploaded in the way ' );
    }
    //$uploadPath='uploads';
    // If this folder does not exist, create 1 A 
    if(!file_exists($uploadPath)){
        mkdir( $uploadPath, 0777, true);
        chmod( $uploadPath, 0777 );
    }
    // New file name only 1
    $uniName = md5 ( uniqid( microtime(true),true) ).'.'.$ext;
    $destination = $uploadPath.'/'.$uniName;
    //@ Symbol is designed to prevent customers from seeing error messages 
    if(! @move_uploaded_file($fileInfo['tmp_name'], $destination )){
        exit(' File movement failed ');
    }
    //echo ' File uploaded successfully ';
    //return array(
    //    'newName'=>$destination,
    //    'size'=>$fileInfo['size'],
    //    'type'=>$fileInfo['type']
    //);
    return $destination;
}
?>

The server manipulates the uploaded file:

000.php


<?php
header('content-type:text/html;charset=utf-8');
include_once '00.php';
$fileInfo=$_FILES['myfile'];
$allowExt=array('jpeg','jpg','png','gif','html','txt');// Modify the type of files allowed to be uploaded, which is ('jpeg','jpg','png','gif','html','txt') You can also add new ones, such as pdf , pptx Wait 
$newName=uploadFile($fileInfo,'imooc',false,$allowExt);// Modify the upload saved folder to be local 'imooc' If there is no such folder, create a 1 A ;//'false' Parameter : Do not check whether the uploaded file is a real picture, because it is necessary to allow uploading files of other types except picture types, such as html , txt
echo $newName;
?>

Finally, the PHP file upload also has more intelligent, more robust PHP single file, multiple single file, multi-file upload function encapsulation

More readers interested in PHP can check the topics of this site: "php File Operation Summary", "PHP Directory Operation Skills Summary", "PHP Common Traversal Algorithms and Skills Summary", "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary" and "PHP Network Programming Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: