php file operation (finally, encapsulate common file functions)

Document information related API

    $filename="./1-file.php";
    //filetype($filename):Get the type of file,Returns the type of file
    echo 'The file type is:',filetype($filename),"\n";//file
    //filesize($filename): get the size of the file, return bytes
    echo 'The file size is:',filesize($filename),"\n";//1214
    //filectime($filename): get the creation time of the file
    echo 'File creation time:',filectime($filename),"\n";//1578719729
    echo 'File creation time:',date('Y year m month d day H:i:s',filectime($filename)),"\n";//2020 January 11, 2013:15:29
    //filemtime($filename): file modification time
    echo 'The modification time of the document is:',date("Y/m/d H:i:s",filemtime($filename)),"\n";//2020/01/11 14:28:20
    //fileatime($filename): last access time of the file
    echo 'The last access time of the file is:',date("Y/m/d H:i:s",fileatime($filename)),"\n";//2020/01/11 14:28:20

Check whether the file is readable, writable, and executable;

    $filename="./1-file.php";
    var_dump(
      is_readable($filename),//bool(true)
      is_writable($filename),//bool(true)
      is_writeable($filename),//bool(true)
      is_executable($filename)//bool(false)
    );

Is? File ($filename): check whether it is a file and the file exists

    var_dump(is_file($filename));//bool(true)

pathinfo(): file path related information

    $filename="./test1.txt";
    $pathinfo=pathinfo($filename);
    print_r($pathinfo);
    /*
    Array
    (
       [dirname] => .
       [basename] => test1.txt
       [extension] => txt
       [filename] => test1
    )
    */
    echo 'File extension:',pathinfo($filename,PATHINFO_EXTENSION),"\n";//txt
    $filename=__FILE__;  
    echo pathinfo($filename,PATHINFO_DIRNAME),"\n";//D:\phpstudy_pro\WWW\phptest
    echo pathinfo($filename,PATHINFO_BASENAME),"\n";//2-path.php
    echo pathinfo($filename,PATHINFO_EXTENSION),"\n";//php
    echo pathinfo($filename,PATHINFO_FILENAME),"\n";//2-path
    //basename(): returns the filename part of the path
    echo basename($filename),"\n";//2-path.php
    echo basename($filename,'.php'),"\n";//2-path
    //dirname(): return path part of filename
    echo dirname($filename),"\n";//D:\phpstudy_pro\WWW\phptest
    //File exists(): check whether the file or directory exists
    var_dump(file_exists($filename));//D:\phpstudy_pro\WWW\phptest\2-path.php:31:bool(true)
    touch('aa.txt');

Document related operations
File create, delete, cut, rename, copy

    //touch($filename):create a file
    $filename='test1.txt';
    var_dump(touch($filename));//bool(true)
    //unlink($filename): delete the specified file
    var_dump(unlink($filename));//bool(true)
    //Delete if detection file exists
    if(file_exists($filename)){
        if(unlink($filename)){
            echo 'File deleted successfully';
        }else{
            echo 'File deletion failed';
        }
    }else{
        echo 'The file to be deleted does not exist';//The file to be deleted does not exist
    }
    touch($filename);
    //rename($filename,$newname):Rename or cut file
    $newname='test111.txt';
    if(rename($filename,$newname)){
        echo 'Rename successful';//Rename successful
    }else{
        echo 'Rename failed';
    }

    //take test123.txt Cut to test Directory test123.txt
     $filename='test123.txt';
     $path='./test/test123.txt';
     if(file_exists($filename)){
       if(rename($filename,$path)){
         echo 'File cut successful';
       }else{
         echo 'File cut failed';//File cut failed
       }
     }else{
       echo 'file does not exist';
     }

    //copy($source,$dest):Copy file
     $source='2-path.php';
     $dest='test123/2-path.php';
     if(copy($source,$dest)){
       echo 'File copied successfully';
     }else{
       echo 'File copy failed';//File copy failed
     }
    //Copying remote files requires opening PHP In the configuration file allow_url_fopen=On
    var_dump(copy('http://blog.phpfamily.org/wp-content/uploads/2016/09/king-1.jpg','./king-1.jpg'));//bool(false)

Document content related operations

    //fopen():Open the specified file in the specified way
    $handle=fopen($filename,'r');
     var_dump($handle);//resource(5) of type (stream)

    //Free(): read the contents of a file in 3 Chinese bytes
     $res=fread($handle,3);
     echo $res,"\n";//this

     $res=fread($handle,3);
     echo $res,"\n";//Yes (read again last time)

    //The filesize() function returns the size of the specified file
     echo filesize($filename),"\n";//55
     $res=fread($handle,filesize($filename));
     echo $res,"\n";//(Continue reading the last time) read all contents
     //A piece of test text
    //This is another test text hh

    //ftell returns the file pointer reading / writing location
     echo ftell($handle),"\n";//55

    var_dump(fread($handle,21));//string(0) ""
    //fseek($handle,$num): reset pointer
    fseek($handle,0);
    var_dump(fread($handle,21));//string(21) "This is a test article"

    //fclose($handle): close file handle
    fclose($handle);
    var_dump(fread($handle,21));//bool(false)

File write

    $filename=__DIR__.'/aa.txt';
    //rb+ Read write opens a binary file, allowing reading and writing data. The file must exist
    $handle=fopen($filename,'rb+');
    //fwrite()/fputs():Write contents
    //Note: fwrite writes content to the file. If there is content before it, overwrite will occur
    fwrite($handle,'abcdef',3);
    fclose($handle);
    //abc Is a test text
    //This is another test text hh

files were added

    //If the file does not exist, it will be created,
    //If the file exists, the contents of the file will be truncated to 0 before writing
    $filename="./aa.txt";
    //ab+ append mode
    $handle=fopen($filename,'ab+');
    fwrite($handle,PHP_EOL.'hello king');
    fclose($handle);
    //abc Is a test text
    //This is another test text hh
    //hello king

truncate file

    $filename='aa.txt';
    $handle=fopen($filename,'rb+');
    //ftruncate():truncate file
    ftruncate($handle,4);
    fclose($handle);
    //abcæ The wonderful effect of the fourth Chinese after being cut off hahahaha

Check whether the file pointer reaches the end of the file

    $filename='aa.txt';
    $handle=fopen($filename,'rb+');
    //feof():Check whether the file pointer reaches the end of the file
    while(!feof($handle)){
      //One character one character read
      // echo fgetc($handle);
      //Read line by line
      echo fgets($handle)."\n";
      //Read line by line and filter HTML sign
      echo strip_tags(fgets($handle))."\n";
      //fgetss() Function to read a line from an open file and filter it out HTML and PHP sign
      echo fgetss($handle);
    }

The fgetcsv() function reads a line from the file pointer and parses the CSV field

    $filename='user.csv';
    $handle=fopen($filename,'rb+');
     $rows=[];
     while($row=fgetcsv($handle)){
       $rows[]=$row;
     }
     print_r($rows);
     
    $handle=fopen('user1.csv','rb+');
    while($row=fgetcsv($handle,0,'-')){
      print_r($row);
    }

The fputcsv() function formats the line as CSV and writes it to an open file

    $filename='user3.csv';
    $handle=fopen($filename,'wb+');

    $data=[
      ['id'=>1,'courseName'=>'ios','courseDesc'=>'this is ios'],
      ['id'=>2,'courseName'=>'android','courseDesc'=>'this is android'],
      ['id'=>3,'courseName'=>'swift','courseDesc'=>'this is swift']
    ];
    foreach($data as $val){
      fputcsv($handle,$val,'-');
    }
    fclose($handle);

Get text from file

    $filename="./aa.txt";
    $string=file_get_contents($filename);
    echo $string;
    //abc Is a test text
    //This is another test text hh
    //hello king

Write content to file
Create write again if it does not exist

    $filename='./aa.txt';
    //file_put_contents($filename,$data):Write content to file
    //$data is in string format
    file_put_contents($filename,'this is a test');
    $res=file_get_contents($filename);
    print_r($res);//this is a test
    echo "\n";
    //If you don't want to overwrite the previous content, you can read out the file first, and then write
     $string=file_get_contents($filename);
     $data=$string.'this is a test';
     file_put_contents($filename,$data);
     $res=file_get_contents($filename);
     print_r($res);//this is a testthis is a test

    //If the file does not exist, file put contents() creates the file
    $filename='aaa.txt';
     $data=[
       ['a','b','c'],
       ['d','e','f']
     ];
     file_put_contents($filename,$data);
     
    //Write to file after array or object serialization
     $data=['a','b','c'];
     $data=serialize($data);
     file_put_contents($filename,$data);
     $res=file_get_contents($filename);
     print_r(unserialize($res));
    //(
    //[0] => a
    //[1] => b
    //[2] => c
    //)

    // Write to a file after converting an array or object to json
     $data=[
       ['a','b','c'],
       ['d','e','f']
     ];
     $data=json_encode($data);
     file_put_contents($filename,$data);
     $res=json_decode(file_get_contents($filename));
     print_r($res);
    //
    //Array
    //(
    //    [0] => Array
    //    (
    //        [0] => a
    //        [1] => b
    //[2] => c
    //        )
    //
    //    [1] => Array
    //(
    //    [0] => d
    //    [1] => e
    //[2] => f
    //        )
    //
    //)

Common function encapsulation:

[encapsulation of common file operation functions]

    /**
     * Create file operation
     * @method create_file
     * @param  string      $filename file name
     * @return boolean                true|false
     */
    function create_file(string $filename){
      //Check whether the file exists, if not, create
      if(file_exists($filename)){
        return false;
      }
      //Check whether the directory exists, if not, create
      if(!file_exists(dirname($filename))){
        //Create directory, you can create multiple levels
        mkdir(dirname($filename),0777,true);
      }
      if(file_put_contents($filename,'')!==false){
        return true;
      }
      return false;
    }
     var_dump(create_file('2.txt'));//bool(true)
     var_dump(create_file('a/4.txt'));//bool(true)


    /**
     * Delete file operation
     * @method del_file
     * @param  string   $filename file name
     * @return boolean             true|false
     */
    function del_file(string $filename){
      //Detect the existence of deleted files,And whether they have permission to operate
      if(!file_exists($filename)||!is_writable($filename)){
        return false;
      }
      if(unlink($filename)){
        return true;
      }
      return false;
    }
     var_dump(del_file('a/3.txt'));//bool(false)


    /**
     * Copy file operation
     * @method copy_file
     * @param  string    $filename file name
     * @param  string    $dest     Specified directory
     * @return boolean              true|false
     */
    function copy_file(string $filename,string $dest){
      //Testing $dest Whether it is the target and whether this directory exists. If it does not exist, create
      if(!is_dir($dest)){
        mkdir($dest,0777,true);
      }
      $destName=$dest.DIRECTORY_SEPARATOR.basename($filename);
      //Check whether there is a file with the same name under the target path
      if(file_exists($destName)){
        return false;
      }
      //Copy file
      if(copy($filename,$destName)){
        return true;
      }
      return false;
    }
    var_dump(copy_file('2.txt','a'));//bool(true)


    /**
     * Rename operation
     * @method rename_file
     * @param  string      $oldName Original document
     * @param  string      $newName New file name
     * @return boolean               true|false
     */
    function rename_file(string $oldName,string $newName){
      //Check the original file and it exists
      if(!is_file($oldName)){
        return false;
      }
      //Get the path of the original file
      $path=dirname($oldName);
      $destName=$path.DIRECTORY_SEPARATOR.$newName;
      if(is_file($destName)){
        return false;
      }
      if(rename($oldName,$newName)){
        return true;
      }
      return false;
    }
    // var_dump(rename_file('2.txt','333.txt'));


    /**
     * Cut file operation
     * @method cut_file
     * @param  string   $filename Original document
     * @param  string   $dest     Target path
     * @return boolean             true|false
     */
    function cut_file(string $filename,string $dest){
      if(!is_file($filename)){
        return false;
      }
      if(!is_dir($dest)){
        mkdir($dest,0777,true);
      }
      $destName=$dest.DIRECTORY_SEPARATOR.basename($filename);
      if(is_file($destName)){
        return false;
      }
      if(rename($filename,$destName)){
        return true;
      }
      return false;
    }
     var_dump(cut_file('333.txt','a'));
     var_dump(cut_file('22.txt','a'));

[document information correlation function encapsulation]

    /**
     * Return file information
     * @method get_file_info
     * @param  string        $filename file name
     * @return mixed                  File information related array | false
     */
    function get_file_info(string $filename){
      if(!is_file($filename)||!is_readable($filename)){
        return false;
      }
      return [
        'atime'=>date("Y-m-d H:i:s",fileatime($filename)),
        'mtime'=>date("Y-m-d H:i:s",filemtime($filename)),
        'ctime'=>date("Y-m-d H:i:s",filectime($filename)),
        'size'=>trans_byte(filesize($filename)),
        'type'=>filetype($filename)
      ];
    }
    var_dump(get_file_info('22.txt'));


    /**
     * Function of byte unit conversion
     * @method trans_byte
     * @param  int        $byte      byte
     * @param  integer    $precision Default precision, keep 2 decimal places
     * @return string                Converted String
     */
    function trans_byte(int $byte,int $precision=2){
      $kb=1024;
      $mb=1024*$kb;
      $gb=1024*$mb;
      $tb=1024*$gb;
      if($byte<$kb){
        return $byte.'B';
      }elseif($byte<$mb){
        return round($byte/$kb,$precision).'KB';
      }elseif($byte<$gb){
        return round($byte/$mb,$precision).'MB';
      }elseif($byte<$tb){
        return round($byte/$gb,$precision).'GB';
      }else{
        return round($byte/$tb,$precision).'TB';
      }
    }
    var_dump(trans_byte(12345678));//string(7) "11.77MB"

[file read / write function encapsulation]

    /**
     * Read file content, return string
     * @method read_file
     * @param  string    $filename file name
     * @return mixed              File content | false
     */
    function read_file(string $filename){
      //Check whether it is a file and the file already exists
      if(is_file($filename) && is_readable($filename)){
        return file_get_contents($filename);
      }
      return false;
    }
    var_dump(read_file('232.txt'));//bool(false)


    /**
     * Read the contents of the file into the array
     * @method read_file_array
     * @param  string          $filename         file name
     * @param  boolean         $skip_empty_lines Filter empty lines or not
     * @return mixed                            array|false
     */
    function read_file_array(string $filename,bool $skip_empty_lines=false){
      if(is_file($filename)&&is_readable($filename)){
        if($skip_empty_lines){
          return file($filename,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
        }else{
          return file($filename);
        }
      }
      return false;
    }
    var_dump(read_file_array('22.txt',true));


    /**
     * Write content to file
     * @method write_file
     * @param  string     $filename file name
     * @param  mixed      $data     Data, arrays and objects need to be processed
     * @return boolean               true|false
     */
    function write_file(string $filename,$data){
      $dirname=dirname($filename);
      //Detect whether the target path exists
      if(!file_exists($dirname)){
        mkdir($dirname,0777,true);
      }
      //Determine whether the content is an array or an object
      if(is_array($data)||is_object($data)){
        //Serialized data
        $data=serialize($data);
      }
      //Write content to file
      if(file_put_contents($filename,$data)!==false){
        return true;
      }else{
        return false;
      }
    }
    var_dump(write_file('c/1.txt',['a','b','c']));


    /**
     * Write content to the file without emptying the previous content
     * @method write_file1
     * @param  string      $filename  file name
     * @param  mixed       $data      data
     * @param  boolean     $clearFlag Empty file or not
     * @return boolean                 true|false
     */
    function write_file1(string $filename,$data,bool $clearFlag=false){
      $dirname=dirname($filename);
      //Detect whether the target path exists
      if(!file_exists($dirname)){
        mkdir($dirname,0777,true);
      }
      //Check if the file exists and is readable
      if(is_file($filename)&&is_readable($filename)){
        //Read the content of the file, and then assemble it with the newly written content
        if(filesize($filename)>0){
          $srcData=file_get_contents($filename);
        }
      }

      //Determine whether the content is an array or an object
      if(is_array($data)||is_object($data)){
        //Serialized data
        $data=serialize($data);
      }
      //Put it together
      $data=$srcData.$data;
      //Write content to file
      if(file_put_contents($filename,$data)!==false){
        return true;
      }else{
        return false;
      }
    }
    var_dump(write_file1('22.txt','hello world'));


    /**
     * Truncate file to specified size
     * @method truncate_file
     * @param  string        $filename file name
     * @param  int           $length   length
     * @return boolean                 true|false
     */
    function truncate_file(string $filename,int $length){
      //Check whether it is a file
      if(is_file($filename)&&is_writable($filename)){
        $handle=fopen($filename,'r+');
        $length=$length<0?0:$length;
        ftruncate($handle,$length);
        fclose($handle);
        return true;
      }
      return false;
    }
    var_dump(truncate_file('22.txt',2));

[file download function encapsulation]

    /**
     * Download File
     * @method down_file
     * @param  string    $filename     file name
     * @param  array     $allowDownExt File types allowed to download
     * @return void
     */
    function down_file(string $filename,array $allowDownExt=array('jpeg','jpg','png','gif','txt','html','php','rar','zip')){
      //Check whether the download file exists and is readable
      if(!is_file($filename)||!is_readable($filename)){
        return false;
      }
      //Check whether the file type allows downloading
      $ext=strtolower(pathinfo($filename,PATHINFO_EXTENSION));
      if(!in_array($ext,$allowDownExt)){
        return false;
      }
      //adopt header()Send header information
      //Tell the browser to output a byte stream
      header('Content-Type:application/octet-stream');

      //Tells the browser that the size of the returned file is calculated in bytes
      header('Accept-Ranges: bytes');

      //Tells the browser the size of the file returned
      header('Accept-Length: '.filesize($filename));

      //Tell the browser to process the file as an attachment, and tell the browser the name of the file finally downloaded
      header('Content-Disposition: attachment;filename=king_'.basename($filename));

      //Read the contents of the file
      readfile($filename);
      exit;

    }

//It is specified that the number of bytes of each read file is 1024 bytes, and the data is output directly
    /**
     * Download File
     * @method down_file
     * @param  string    $filename     file name
     * @param  array     $allowDownExt File types allowed to download
     * @return void
     */
    function down_file1(string $filename,array $allowDownExt=array('jpeg','jpg','png','gif','txt','html','php','rar','zip')){
      //Check whether the download file exists and is readable
      if(!is_file($filename)||!is_readable($filename)){
        return false;
      }
      //Check whether the file type allows downloading
      $ext=strtolower(pathinfo($filename,PATHINFO_EXTENSION));
      if(!in_array($ext,$allowDownExt)){
        return false;
      }
      //adopt header()Send header information

      //Tell the browser to output a byte stream
      header('Content-Type:application/octet-stream');

      //Tells the browser that the size of the returned file is calculated in bytes
      header('Accept-Ranges: bytes');

      $filesize=filesize($filename);
      //Tells the browser the size of the file returned
      header('Accept-Length: '.$filesize);

      //Tell the browser to process the file as an attachment, and tell the browser the name of the file finally downloaded
      header('Content-Disposition: attachment;filename=king_'.basename($filename));

      //Read the contents of the file

      //It is specified that the number of bytes of each read file is 1024 bytes, and the data is output directly
      $read_buffer=1024;
      $sum_buffer=0;
      $handle=fopen($filename,'rb');
      while(!feof($handle) && $sum_buffer<$filesize){
        echo fread($handle,$read_buffer);
        $sum_buffer+=$read_buffer;
      }
      fclose($handle);
      exit;
    }

    //When the specific page is called
    require_once 'file.func.php';
    $filename=$_GET['filename'];
    down_file1($filename);

[file upload function encapsulation]

    /**
     * Single file upload
     * @method upload_file
     * @param  array       $fileInfo   The information of the uploaded file is an array
     * @param  string      $uploadPath Default path for file upload
     * @param  boolean     $imageFlag  Whether to detect real pictures
     * @param  array       $allowExt   File types allowed to upload
     * @return mixed                  Return the final save path and name of the file successfully, and return false in failure
     */
    function upload_file(array $fileInfo,string $uploadPath='./uploads',bool $imageFlag=true,array $allowExt=array('jpeg','jpg','png','gif'),int $maxSize=2097152){
      define('UPLOAD_ERRS',[
        'upload_max_filesize'=>'Exceeded PHP In profile upload_max_filesize Option value',
        'form_max_size'=>'Form exceeded MAX_FILE_SIZE Option value',
        'upload_file_partial'=>'File part Uploaded',
        'no_upload_file_select'=>'No file upload selected',
        'upload_system_error'=>'System error',
        'no_allow_ext'=>'Illegal file type',
        'exceed_max_size'=>'Exceeded the maximum allowed upload',
        'not_true_image'=>'File is not a real picture',
        'not_http_post'=>'File not passed HTTP POST Uploaded by',
        'move_error'=>'File move failed'
      ]);

      //Check whether there are errors in uploading
      if($fileInfo['error']===UPLOAD_ERR_OK){
        //Detect upload file type
        $ext=strtolower(pathinfo($fileInfo['name'],PATHINFO_EXTENSION));
        if(!in_array($ext,$allowExt)){
          echo  UPLOAD_ERRS['no_allow_ext'];
          return false;
        }
        //Check whether the size of the uploaded file conforms to the specification
        if($fileInfo['size']>$maxSize){
          echo UPLOAD_ERRS['exceed_max_size'];
          return false;
        }
        //Check whether it is a real picture
        if($imageFlag){
          if(@!getimagesize($fileInfo['tmp_name'])){
            echo UPLOAD_ERRS['not_true_image'];
            return false;
          }
        }
        //Check whether the file passes HTTP POST Uploaded by
        if(!is_uploaded_file($fileInfo['tmp_name'])){
          return UPLOAD_ERRS['not_http_post'];
        }
        //Check whether the target directory exists, if not, create
        if(!is_dir($uploadPath)){
          mkdir($uploadPath,0777,true);
        }
        //Generate unique file names to prevent duplicate names from overwriting
        $uniName=md5(uniqid(microtime(true),true)).'.'.$ext;
        $dest=$uploadPath.DIRECTORY_SEPARATOR.$uniName;

        //move file
        if(@!move_uploaded_file($fileInfo['tmp_name'],$dest)){
          echo UPLOAD_ERRS['move_error'];
          return false;
        }
        echo 'File uploaded successfully';
        return $dest;
      }else{
        switch($fileInfo['error']){
          case 1:
          // $mes='Exceeded PHP In profile upload_max_filesize Option value';
          $mes=UPLOAD_ERRS['upload_max_filesize'];
          break;
          case 2:
          $mes=UPLOAD_ERRS['form_max_size'];
          break;
          case 3:
          $mes=UPLAOD_ERRS['upload_file_partial'];
          break;
          case 4:
          $mes=UPLOAD_ERRS['no_upload_file_select'];
          break;
          case 6:
          case 7:
          case 8:
          $mes=UPLAOD_ERRS['upload_system_error'];
          break;
        }
        echo $mes;
        return false;
      }
    }

    //When the specific page is called
    require_once 'file.func.php';
    $fileInfo=$_FILES['myFile'];
    var_dump(upload_file($fileInfo));

[file compression and decompression function encapsulation]

    /**
     * Compress a single file
     * @method zip_file
     * @param  string   $filename file name
     * @return boolean             true|false
     */
    function zip_file(string $filename){
      if(!is_file($filename)){
        return false;
      }
      $zip=new ZipArchive();
      $zipName=basename($filename).'.zip';
      //Open the specified compression package, create if it does not exist, and overwrite if it exists
      if($zip->open($zipName,ZipArchive::CREATE|ZipArchive::OVERWRITE)){
        //Add files to the package
        if($zip->addFile($filename)){
          $zip->close();
          @unlink($filename);
          return true;
        }else{
          return false;
        }
      }else{
        return false;
      }
    }
    // var_dump(zip_file('22.txt'));
    // func_get_args
    // test1.zip



    /**
     * Multi file compression
     * @method zip_files
     * @param  string    $zipName Name of the compressed package, end of. zip
     * @param  string     $files   Need to compress file name, can be multiple
     * @return boolean             true|false
     */
    function zip_files(string $zipName,...$files){
      //Check whether the compressed package name is correct
      $zipExt=strtolower(pathinfo($zipName,PATHINFO_EXTENSION));
      if('zip'!==$zipExt){
        return false;
      }
      $zip=new ZipArchive();
      if($zip->open($zipName,ZipArchive::CREATE|ZipArchive::OVERWRITE)){
        foreach($files as $file){
          if(is_file($file)){
            $zip->addFile($file);
          }
        }
        $zip->close();
        return true;
      }else{
        return false;
      }
    }
    // var_dump(zip_files('test1.zip','22.txt'));
    // var_dump(zip_files('test2.zip','doUpload.php','downLoad.html','upload.html'));



        /**
         * decompression
         * @method unzip_file
         * @param  string     $zipName Package name
         * @param  string     $dest    Extract to the specified directory
         * @return boolean              true|false
         */
        function unzip_file(string $zipName,string $dest){
          //Check whether the compressed package to be decompressed exists
          if(!is_file($zipName)){
            return false;
          }
          //Detect whether the target path exists
          if(!is_dir($dest)){
            mkdir($dest,0777,true);
          }
          $zip=new ZipArchive();
          if($zip->open($zipName)){
            $zip->extractTo($dest);
            $zip->close();
            return true;
          }else{
            return false;
          }
        }
        // var_dump(unzip_file('test2.zip','a'));

Details of $'FILES parameter:
$_FILES["file"]["name"] – the name of the uploaded file
$_FILES["file"]["type"] – the type of the uploaded file
$_FILES["file"]["size"] – the size of the uploaded file in bytes
$_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server
$_FILES["file"]["error"] – error code caused by file upload


The value of ["error"] in $'u FILES["file"]["error"]:
UPLOAD_ERR_OK
0: no error occurred, file upload succeeded
UPLOAD_ERR_INI_SIZE
1: The uploaded file exceeds the limit of the upload [Max] filesize (2m by default) option in php.ini
UPLOAD_ERR_FORM_SIZE
2: The size of the uploaded file exceeds the value specified by the max file size option in the HTML form
UPLOAD_ERR_PARTIAL
3: Only part of the file is uploaded
UPLOAD_ERR_NO_FILE
4: No files uploaded
5: Transfer file size is 0

Tags: PHP iOS Android Swift

Posted on Sat, 11 Jan 2020 00:44:16 -0800 by FrostedFlakes