Home Backend Development PHP Tutorial PHP package file example

PHP package file example

Dec 25, 2017 pm 02:58 PM
php Example document

很多时候我们可能需要将很多小文件打包提供给用户下载,那具体如何实现呢?本文主要介绍了PHP打包文件实例,直接给出PHP打包文件的示例代码,希望对大家有所帮助。

大概需求:

每一个订单都有多个文件附件,在下载的时候希望对当前订单的文件自动打包成一个压缩包下载

细节需求:当前订单号_年月日+时间.zip  例如:

1.生成压缩文件,压缩文件名格式:

2.压缩文件存放在根目录 /upload/zipfile/年月/自定义的压缩文件名.zip

3.点击下载压缩包,系统开始对压缩文件打包,打包完成后自动开始下载

4.为了防止暴露压缩包文件路径,需要对下载的压缩包文件名改名

 

具体操作模式请见下面的代码:

文件路径:

压缩包文件存放路径:/upload/zipfile/

上传的附件存放路径:/upload/file/

1.基本配置文件文件 config.inc.php放在系统根目录

 


1

2

3

4

5

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);

Copy after login


2.压缩包程序代码文件 getzip.php


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

header("Content-type: text/html; charset=utf-8");

require_once '../config.inc.php'; //载入配置路径配置文件

$arrfiles = array(SYS_UPLOAD . '/1.jpg',

  SYS_UPLOAD . '/x.jpg',); //这里是附件的文件数组

$orderNum = '888'; //订单号

$downFileName = 'tieniu.zip'; //下载的文件名 如果为空那么就是系统自定义名称 如果指定就显示指定名字

$zipUrl = create_zip($arrfiles, $orderNum); //生成的压缩文件名词

file_down($zipUrl, $downFileName); //提供http下载,并可以进行重命名下载文件,建议重命名,防止路径猜解

 

/*

 * 生成压缩包文件名

 * @param [String] $orderNum 订单号

 * @return [String] 返回带有绝对路径的订单号的压缩文件名

 */

 

function get_zipname($orderNum) {

  $zipName = SYS_DOWNLOAD . '/' . date('Ym') . '/' . $orderNum . '_' . date("Ymd_Hi") . '.zip';

  return $zipName;

}

 

/*

 * 按照特定需求打包压缩包的目录结构设置

 */

 

function pack_object() {

   

}

 

/*

 * 生成压缩包

 * @param [Array] $arrfiles 带有绝对路径的文件数组

 * @param [String] $orderNum 订单号

 * @return [String] 返回带有绝对路径的订单号的压缩文件名 如如果失败返回 FALSE

 */

 

function create_zip($arrfiles, $orderNum) {

  $zipName = get_zipname($orderNum); //获得文件名

  dir_create(dirname($zipName)); //建立生成压缩文件的目录

  $zip = new ZipArchive();

  if ($zip->open($zipName, ZIPARCHIVE::CREATE) !== TRUE) {

    return FALSE;

  }

  foreach ($arrfiles as $path) {

    if (is_file($path)) {//判断文件是否存在

      $zip->addFile($path, basename($path)); //把文件加入到压缩包中

    }

  }

  $zip->close();

  return $zipName;

}

 

/*

 * 处理文件目录

 * @param [Array] $arrfiles 带有绝对路径的文件数组

 * @param [String] $dirpath 文件路径

 * @return [String] 返回处理的文件路径,方便生成文件目录

 */

 

function dir_path($dirpath) {

  $dirpath = str_replace('\\', '/', $dirpath);

  if (substr($dirpath, -1) != '/')

    $dirpath = $dirpath . '/';

  return $dirpath;

}

 

/*

 * 生成文件目录

 * @param [String] $path 文件路径

 * @return [String] 返回生成的文件目录结构

 */

 

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] . &#39;/&#39;;

    if (is_dir($cur_dir))

      continue;

    @mkdir($cur_dir);

    if (SYS_CHMOD)

      @chmod($cur_dir, SYS_CHMOD);

    if (!is_file($cur_dir . &#39;/index.html&#39;) && !is_file($cur_dir . &#39;/index.php&#39;))

      file_copy(SYS_ROOT . &#39;/upload/index.html&#39;, $cur_dir . &#39;/index.html&#39;);

  }

 

  return is_dir($path);

}

 

/*

 * 文件COPY

 * @param [String] $from copy源文件

 * @param [String] $to copy文件目的地

 * @return [Bool] 成功 ture 失败 false

 */

 

function file_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;

  }

}

 

/*

 * 文件下载处理函数

 * @param [String] $file 文件路径

 * @param [String] $filename 下载时间重新命名的文件名

 * @param [String] $data 下载文件填装的数据内容

 */

 

function file_down($file, $filename = &#39;&#39;, $data = &#39;&#39;) {

  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[&#39;HTTP_USER_AGENT&#39;], &#39;MSIE&#39;) !== false) {

    header(&#39;Cache-Control: must-revalidate, post-check=0, pre-check=0&#39;);

    header(&#39;Pragma: public&#39;);

  } else {

    header(&#39;Pragma: no-cache&#39;);

  }

  header(&#39;Expires: &#39; . gmdate(&#39;D, d M Y H:i:s&#39;) . &#39; GMT&#39;);

  header(&#39;Content-Encoding: none&#39;);

  header(&#39;Content-Length: &#39; . $filesize);

  header(&#39;Content-Disposition: attachment; filename=&#39; . $filename);

  header(&#39;Content-Type: &#39; . $filetype);

  if ($data) {

    echo $data;

  } else {

    readfile($file);

  }

  exit;

}

 

function file_ext($filename) {

  return strtolower(trim(substr(strrchr($filename, &#39;.&#39;), 1)));

}

 

//此函数未用到,用来做整个目录的打包下载

function listdir($start_dir = &#39;.&#39;) {

  $files = array();

  if (is_dir($start_dir)) {

    $fh = opendir($start_dir);

    while (($file = readdir($fh)) !== false) {

      if (strcmp($file, &#39;.&#39;) == 0 || strcmp($file, &#39;..&#39;) == 0)

        continue;

      $filepath = $start_dir . &#39;/&#39; . $file;

      if (is_dir($filepath))

        $files = array_merge($files, listdir($filepath));

      else

        array_push($files, $filepath);

    }

    closedir($fh);

  } else {

    $files = false;

  }

  return $files;

}

Copy after login


 

3.PHP程序生成压缩文件需要用到压缩类:ZipArchive

这个是php的扩展类,自php5.2版本以后就已经支持这个扩展,如果你在使用的时候出现错误,查看下php.ini里面的extension=php_zip.dll前面的分号有没有去掉,然后再重启Apache这样才能使用这个类库。


相关推荐:

php 文件分割与合并(断点续传)

php 文件类型的判断示例代码

简单谈谈 php 文件锁

The above is the detailed content of PHP package file example. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1660
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles