PHP Package File Instance

Source: Internet
Author: User
Tags file copy strcmp ziparchive custom name
Many times we may need to package a lot of small files to provide users with the download, how to do it? This article mainly introduces the PHP package file instance, directly to the PHP package file sample code, I hope to help you.

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__)));d efine (' Sys_upload ', Sys_root. ') /upload/file ');d efine (' Sys_download ', sys_root. /upload/zipfile ');d efine (' Sys_win ', Strpos (Strtoupper (php_os), ' WIN ')!== false? true:false);d efine (' 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 attachment files $ordernum = ' 888 '; Order number $downfilename = ' tieniu.zip '; Download file name if it is empty then it is the system custom name if specified to display the specified name $zipurl = Create_zip ($arrfiles, $orderNum); Generated compressed file noun file_down ($zipUrl, $downFileName); Provide HTTP download, and can rename download file, suggest renaming, prevent path guess/* * Generate Compressed Package file name * @param [string] $orderNum order number * @return [string] Returns the compressed file name of the order number with absolute path * * function Get_zipname ($orderNum) {$zipName = Sys_download. '/' . Date (' Ym '). '/' . $orderNum. '_' . Date ("Ymd_hi").  '. zip '; return $zipName;} /* Package Compressed package directory structure settings according to specific requirements */function Pack_object () {}/* * generates a compressed package * @param [array] $arrfiles an array of files with an absolute path * @param [String] $  Ordernum Order number * @return [String] Returns the compressed file name of the order number with the absolute path if the failure returns FALSE */function create_zip ($arrfiles, $orderNum) {$zipName = Get_zipname ($orderNum); Get filename dir_create (dirname ($zipName));  Create a directory that generates compressed files $zip = new ziparchive (); if ($zip->open ($zipName, ziparchive::create)!== TRUE) {return FALSE; } foreach ($arrfiles as $path) {if (Is_file ($path)) {//To determine if the file exists $zip->addfile ($path, basename ($path));//Add File  into the 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 file directory generation *  /function Dir_path ($dirpath) {$dirpath = str_replace (' \ \ ', '/', $dirpath); if (substr ($dirpath,-1)! = '/') $dirpath = $dirpath.  '/'; return $dirpath;}     /* * Generate file directory * @param [string] $path file path * @return [string] Returns the resulting file directory structure */function dir_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] success Ture failure false */function F  Ile_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  */function File_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; function File_ext ($filename) {return Strtolower (Trim (substr (STRRCHR ($filename, '. '), 1)));} This function is not used to do the packaged download function Listdir for the entire directory ($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.


Related recommendations:

PHP File Segmentation and Merging (breakpoint continuation)

Sample code for PHP file type determination

Simply talk about PHP file locks

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.