PHP Implementation of Single File Multiple Single File Multiple File Upload Function Encapsulation Example

  • 2021-12-19 06:13:31
  • OfStack

This article describes the example of PHP implementation of single file, multiple single file, multi-file upload function encapsulation. Share it for your reference, as follows:

Form:

s.php

To be able to select more than one file at a time when selecting upload files, add multiple="multiple" And pay attention name="myFile1" And name="myFile[]" The difference between single file and multi-file upload.


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> Untitled document </title>
</head>
<body>
<form action="sss.php" method="post" enctype="multipart/form-data">
  <input type="file" name="myFile1" /><br/>
  <input type="file" name="myFile2" /><br/>
  <input type="file" name="myFile[]" /><br/>
  <input type="file" name="myFile[]" /><br/>
  <input type="file" name="myFile[]" multiple="multiple"/><br/>
  <input type="submit" value=" Upload a file "/>
</form>
</body>
</html>

Encapsulation of upload function:

ss.php


<?php
header('Content-Type:text/html;charset=utf-8');
// Build uploaded file information 
function getFiles(){
    $i=0;
    foreach($_FILES as $file){
        // Because at this time $_FILES It's a 3 Dimension array, and when uploading a single file or multiple files, the first of the array 1 Dimension types are different, so you can judge whether you upload a single file or multiple files 
        if(is_string($file['name'])){
        // If it is a single file 
            $files[$i]=$file;
            $i++;
        }elseif(is_array($file['name'])){
        // If it is multiple files 
            foreach($file['name'] as $key=>$val){
                $files[$i]['name']=$file['name'][$key];
                $files[$i]['type']=$file['type'][$key];
                $files[$i]['tmp_name']=$file['tmp_name'][$key];
                $files[$i]['error']=$file['error'][$key];
                $files[$i]['size']=$file['size'][$key];
                $i++;
            }
        }
    }
    return $files;
}
// Upload for single file, multiple single files and multiple files 
// The files allowed to upload by default are only picture types, and only these picture types :$allowExt=array('jpeg','jpg','png','gif'); And check whether the uploaded file is a real picture $flag=true
// The default upload and save folder is local 'uploads' Folder, the maximum size of files allowed to be uploaded 2M
function uploadFile($fileInfo,$path='./uploads',$flag=true,$allowExt=array('jpeg','jpg','png','gif'),$maxSize=2097152){
    // Judgment error number 
    if($fileInfo['error']===UPLOAD_ERR_OK){
        // Detect the size of uploaded files 
        if($fileInfo['size']>$maxSize){
            $res['mes']=$fileInfo['name'].' The uploaded file is too large ';
        }
        $ext=getExt($fileInfo['name']);
        // Detect the file type of the uploaded file 
        if(!in_array($ext,$allowExt)){
            $res['mes']=$fileInfo['name'].' Illegal file type ';
        }
        // Check whether it is a real picture type 
        if($flag){
            if(!getimagesize($fileInfo['tmp_name'])){
                $res['mes']=$fileInfo['name'].' Is not a real picture type ';
            }
        }
        // Check whether the file is passed HTTP POST Uploaded up 
        if(!is_uploaded_file($fileInfo['tmp_name'])){
            $res['mes']=$fileInfo['name'].' File is not passed through HTTP POST Uploaded in the way ';
        }
        if( $res ) return $res; // If you don't want to display an error message, use the if( @$res ) return $res;
        //$path='./uploads';
        // If this folder does not exist, create 1
        if(!file_exists($path)){
            mkdir($path,0777,true);
            chmod($path,0777);
        }
        // New file name only 1
        $uniName=getUniName();
        $destination=$path.'/'.$uniName.'.'.$ext;
        //@ Symbol is to prevent customers from seeing error messages, and can also be deleted 
        if(!@move_uploaded_file($fileInfo['tmp_name'],$destination)){
            $res['mes']=$fileInfo['name'].' File movement failed ';
        }
        $res['mes']=$fileInfo['name'].' Upload succeeded ';
        $res['dest']=$destination;
        return $res;
    }else{
        // Match error message 
        // Attention! Error message does not 5
        switch($fileInfo['error']){
            case 1:
                $res['mes'] = ' Upload files exceeded PHP In the configuration file upload_max_filesize The value of the option ';
                break;
            case 2:
                $res['mes'] = ' Beyond HTML Form MAX_FILE_SIZE Limit size ';
                break;
            case 3:
                $res['mes'] = ' The file part is uploaded ';
                break;
            case 4:
                $res['mes'] = ' Upload file not selected ';
                break;
            case 6:
                $res['mes'] = ' Temporary directory not found ';
                break;
            case 7:
                $res['mes'] = ' File write failure ';
                break;
            case 8:
                $res['mes'] = ' The uploaded file is PHP Extension program interrupt ';
                break;
        }
        return $res;
    }
}
?>

common.ss.php


<?php
// These two functions can also 1 Lifting and placing ss.php Go inside 
// Get the file extension 
function getExt($filename){
    return strtolower(pathinfo($filename,PATHINFO_EXTENSION));
}
// Generate only 1 String 
function getUniName(){
    return md5(uniqid(microtime(true),true));
}
?>

Operation of files after uploading:


<?php
header("content-type:text/html;charset=utf-8");
require_once 'ss.php';
require_once 'common.ss.php';
$files=getFiles();
// 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 
$allowExt=array('jpeg','jpg','png','gif','html','txt');
foreach($files as $fileInfo){
    // 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
    $res=uploadFile($fileInfo,'imooc',false,$allowExt);
    echo $res['mes'],'<br/>';
    $uploadFiles[]=$res['dest'];// If you don't want to display an error message, use the @$uploadFiles[]=$res['dest'];
}
$uploadFiles=array_values(array_filter($uploadFiles));// This is easy to save to the database 
print_r($uploadFiles);// Print, view, upload and save results 
?>

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: