PHP generated compressed file Development example

Source: Internet
Author: User
Tags file copy strcmp ziparchive custom name

Approximate requirements:

Each order has a number of file attachments, in the download of the time you want to the current order files automatically packaged into a compressed package download

Details Required: Current order number _ Month Day + time. Zip For example:

1. Generate compressed files, compressed file name format:

2. Compressed files are stored in the root directory/upload/zipfile//Custom compressed file name. zip

3. Click the download package, the system begins to package the compressed file, and automatically start the download after packaging is finished

4. To prevent exposing the compressed package file path, you need to rename the downloaded archive file name

Please see the following code for the specific operating mode:

File path:

Compressed package file storage path:/upload/zipfile/

Uploaded attachment Storage path:/upload/file/

1. Basic Profile file config.inc.php placed in the system root directory

 define  (' Sys_root ', str_replace  (" \ \ ", '/', dirname  (__file__  ))); define  (' Sys_upload ', Sys_root. ') /upload/file '  define  (' Sys_download ', Sys_root. ') /upload/zipfile '  define  (' Sys_win ', strpos  (strtoupper  (php_os ), ' WIN ')!== false ? true : false   define  (' Sys_chmod ', (' 0777 ' &&! Sys_win)? ' 0777 ': 0); 

2. Compress package program code files getzip.php

Header("content-type:text/html; Charset=utf-8 ");require_once‘.. /config.inc.php ';//load Configuration path configuration file$arrfiles=Array(Sys_upload. '/1.jpg ',Sys_upload. '/x.jpg ',);//here is an array of attachments to the file$orderNum= ' 888 ';//Order Number$downFileName= ' Tieniu.zip ';//If the file name is empty then the system custom name displays the specified name if specified$ZIPURL= Create_zip ($arrfiles,$orderNum);//generated compressed file nounsFile_down ($ZIPURL,$downFileName);//provide HTTP download, and can rename download file, suggest renaming, prevent path guessing/** Generate compressed Package file name * @param [string] $orderNum order number * @return [string] to return the compressed file name of the order number with the absolute path*/functionGet_zipname ($orderNum) {    $zipName= Sys_download. ‘/‘ .Date(' Ym '). ‘/‘ .$orderNum. ‘_‘ .Date("Ymd_hi"). '. Zip '; return $zipName;}/** directory structure settings for packaging compressed packages according to specific requirements*/functionPack_object () {}/** Generate a compressed package * @param [array] $arrfiles an array of files with an absolute path * @param [string] $orderNum order number * @return [string] Returns a compressed file with an absolute path to the order number Name as if failure returns FALSE*/functionCreate_zip ($arrfiles,$orderNum) {    $zipName= Get_zipname ($orderNum);//Get file nameDir_create (dirname($zipName));//Create a directory to generate compressed files    $zip=Newziparchive (); if($zip->open ($zipName, ziparchive::create)!==TRUE) {        return FALSE; }    foreach($arrfiles  as $path) {        if(Is_file($path)) {//determine if a file exists            $zip->addfile ($path,basename($path));//adding files to a compressed package        }    }    $zip-Close (); return $zipName;}/** Process file directory * @param [array] $arrfiles an array of files with an absolute path * @param [string] $dirpath file path * @return [string] Returns the file path processed to facilitate the creation of the text Parts Directory*/functionDir_path ($dirpath) {    $dirpath=Str_replace(‘\\‘, ‘/‘,$dirpath); if(substr($dirpath,-1)! = '/')        $dirpath=$dirpath. ‘/‘; return $dirpath;}/** Generate file directory * @param [string] $path file path * @return [string] to return the resulting file directory structure*/functionDir_create ($path) {    if(Is_dir($path))        return true; $dir=Str_replace(Sys_download. ‘/‘, ‘‘,$path); $dir= Dir_path ($dir); $temp=Explode(‘/‘,$dir); $cur _dir= Sys_download. ‘/‘; $max=Count($temp)-1;  for($i= 0;$i<$max;$i++) {        $cur _dir.=$temp[$i] . ‘/‘; if(Is_dir($cur _dir))            Continue; @mkdir($cur _dir); if(sys_chmod) @chmod($cur _dir,sys_chmod); if(!Is_file($cur _dir. '/index.html ') &&!Is_file($cur _dir. '/index.php ')) file_copy (Sys_root. '/upload/index.html ',$cur _dir. '/index.html '); }    return Is_dir($path);}/** File copy * @param [string] $from copy source file * @param [string] $to Copy File destination * @return [Bool] succeeded Ture failed false*/functionFile_copy ($from,$to) {dir_create (dirname($to)); if(Is_file($to) &&sys_chmod) @chmod($to,sys_chmod); if(@Copy($from,$to)) {        if(sys_chmod) @chmod($to,sys_chmod); return true; } Else {        return false; }}/** File Download handler function * @param [string] $file file path * @param [string] $filename download time rename file name * @param [string] $data download file filled data Content*/functionFile_down ($file,$filename= ",$data= ' ') {    if(!$data&&!Is_file($file))        Exit; $filename=$filename?$filename:basename($file); $filetype= File_ext ($filename); $filesize=$data?strlen($data) :filesize($file); Ob_end_clean(); @Set_time_limit(0); if(Strpos($_server[' Http_user_agent '], ' MSIE ')!==false) {        Header(' Cache-control:must-revalidate, post-check=0, pre-check=0 '); Header(' Pragma:public '); } Else {        Header(' Pragma:no-cache '); }    Header(' Expires: '.gmdate(' d, D M Y h:i:s '). ' GMT '); Header(' Content-encoding:none '); Header(' Content-length: '.$filesize); Header(' Content-disposition:attachment; Filename= '.$filename); Header(' Content-type: '.$filetype); if($data) {        Echo $data; } Else {        ReadFile($file); }    Exit;}functionFile_ext ($filename) {    return Strtolower(Trim(substr(STRRCHR($filename, '. '), 1)));}//This function is not used to make a package download for the entire directoryfunctionListdir ($start _dir= '. ') {    $files=Array(); if(Is_dir($start _dir)) {        $fh=Opendir($start _dir);  while(($file=Readdir($fh)) !==false) {            if(strcmp($file, ‘.‘) = = 0 | |strcmp($file, ‘..‘) = = 0)                Continue; $filepath=$start _dir. ‘/‘ .$file; if(Is_dir($filepath))                $files=Array_merge($files, Listdir ($filepath)); Else                Array_push($files,$filepath); }        Closedir($fh); } Else {        $files=false; }    return $files;}

3.PHP program to generate compressed files need to use compression class: Ziparchive

This is the PHP extension class, since the php5.2 version has been supported this extension, if you are using the error, check the php.ini inside the EXTENSION=PHP_ Zip.dll in front of the semicolon has not been removed, and then restart Apache to use this class library.

PHP generated compressed file Development example

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.