---
title: "PHP上传进度条深度解析"
author: "xinlanzero"
date: "2011-09-11T15:36:54Z"
tags: []
categories: ["Web前端"]
slug: "php"
draft: false
lastmod: "2011-09-11T15:36:54Z"
id: 1170129
url: "https://xinlanzero.iteye.com/blog/1170129"
---

随着互联网的发展，越来越多的技术开始注重用户体验，以人为本才是长久之道，于是在上传的时候，大家都不再满足一个单一的“浏览”按钮，纷纷推出了带上传进度条的功能。而作为解释型语言的PHP，如何做到对上传文件的检测，如何实现上传进度条以其背后的原理，54chen将在本文中一步步展开。

**一. 实现篇**

一般情况，用PHP实现上传进度条就下面两种方法：

1.APC扩展（作者是PHP的创始人，5.2后PHP已经加入APC扩展）

2.PECL扩展模块 uploadprogress

不论是APC还是uploadprogress，都需要编译源码，因为原有的PHP函数根本不可能读取到临时文件夹里的东西。下面来看如何使用以及关键的代码：

**APC实现方法:**

1.安装APC

2.配置php.ini，设置参数 apc.rfc1867=1

3.关键代码：

> if ($\_SERVER\['REQUEST\_METHOD'] == ‘POST’) {  //上传请求
> 
> $status = apc\_fetch(‘upload\_’ . $\_POST\['APC\_UPLOAD\_PROGRESS']);
> 
> $status\['done'] = 1;
> 
> echo json\_encode($status);  //输出给用户端页面里的ajax调用，相关文档请自己寻找
> 
> exit;
> 
> } elseif (isset($\_GET\['progress\_key'])) {   //读取上传进度
> 
> $status = apc\_fetch(‘upload\_’.$\_GET\['progress\_key']);
> 
> echo json\_encode($status);
> 
> exit;
> 
> }

**uploadprogress实现方法：**

1.使用PECL 安装uploadprogress

2.php.ini里面设置 uploadprogress.file.filename\_template = “/tmp/upd\_%s.txt”

3.关键代码：

> if($\_SERVER\['REQUEST\_METHOD']==’POST’) {
> 
> if (is\_uploaded\_file($\_FILES\['upfile']\['tmp\_name'])) {
> 
> $upload\_dir = ‘your\_path/’;
> 
> $ext        = strrchr($\_FILES\['video']\['name'], ‘.’);
> 
> $sessid     = $\_POST\['UPLOAD\_IDENTIFIER'] ;
> 
> $tmpfile    = $upload\_dir . $sessid;
> 
> $sessfile   = $upload\_dir . $sessid .$ext;
> 
> if (move\_uploaded\_file($\_FILES\['upfile']\['tmp\_name'],$tmpfile)) {
> 
> //上传成功
> 
> }
> 
> }
> 
> } elseif (!empty($\_GET\['sessid'])) {
> 
> header(“Expires: Mon, 26 Jul 1997 05:00:00 GMT”);
> 
> header(“Last-Modified: ” . gmdate(“D, d M Y H:i:s”) . ” GMT”);
> 
> header(“Cache-Control: no-store, no-cache, must-revalidate”);
> 
> header(“Cache-Control: post-check=0, pre-check=0″, false);
> 
> header(“Pragma: no-cache”);
> 
> header(“Content-Type:text/html;charset=UTF-8″);
> 
> $unique\_id = $\_GET\['sessid'];
> 
> $uploadvalues = uploadprogress\_get\_info($unique\_id);
> 
> if (is\_array($uploadvalues)) {
> 
> echo json\_encode($uploadvalues);
> 
> } else {
> 
> //读取进度失败，另外处理逻辑
> 
> }
> 
> }

**二. 原理篇**

注意上一篇中的红色函数。

下载到uploadprogress1.0.1进行源码分析，在代码中作了注释。

> static void uploadprogress\_file\_php\_get\_info(char * id, zval * return\_value)
> 
> {
> 
> char s\[1024];
> 
> char * filename;
> 
> char * template;
> 
> FILE \*F;
> 
> TSRMLS\_FETCH();
> 
> template = INI\_STR(“uploadprogress.file.filename\_template”); &lt;&lt;这里读取设置好的模板
> 
> if (strcmp(template, “”) == 0)  {
> 
> return;
> 
> } else {
> 
> filename = uploadprogress\_mk\_filename( id, template );&lt;&lt;&lt;存在的话，会创建
> 
> if (!filename) return;
> 
> F = VCWD\_FOPEN(filename, “rb”);
> 
> if (F) {
> 
> array\_init(return\_value);
> 
> while ( fgets(s, 1000, F) ) {&lt;&lt;&lt;从流中读取一字符串 \*s结果数据的首地址；1000-1:一次读入数据块的长度,其默认值为1k，即1024;F文件指针
> 
> char \*k, \*v, \*e;
> 
> int index = 0;
> 
> e = strchr(s,’='); &lt;&lt;&lt;查找字符串s中首次出现字符=的位置
> 
> if (!e) continue;
> 
> \*e = 0; /* break the line into 2 parts \*/
> 
> v = e+1;
> 
> k = s;
> 
> /* trim spaces in front of the name/value \*/
> 
> while (\*k && \*k &lt;= 32) k++;
> 
> while (\*v && \*v &lt;= 32) v++;
> 
> /* trim spaces everywhere in the name \*/
> 
> for (e=k; \*e; e++) if (\*e &lt;= 32) { \*e = 0; break; }
> 
> /* trim spaces only at the end of the value \*/
> 
> /* http://pecl.php.net/bugs/bug.php?id=14525 \*/
> 
> //for (e=v; \*e; e++) if (\*e &lt;= 32) { \*e = 0; break; }
> 
> if (v != NULL) {&lt;&lt;&lt;当文件有内容时
> 
> for (index = strlen(v); index &gt; 0; index–) {
> 
> if (v\[index] &gt; 32) break;&lt;&lt;&lt;累计
> 
> v\[index] = 0;
> 
> }
> 
> }
> 
> add\_assoc\_string( return\_value, k, v, 1 );
> 
> }
> 
> fclose(F);
> 
> }
> 
> if (filename) efree(filename);
> 
> return;
> 
> }
> 
> }

在源码中还能发现:

> PHP\_MINIT\_FUNCTION(uploadprogress)
> 
> {
> 
> REGISTER\_INI\_ENTRIES();
> 
> php\_rfc1867\_callback = uploadprogress\_php\_rfc1867\_file;
> 
> return SUCCESS;
> 
> }

在MINIT中修改了php\_rfc1867\_callback，抽取uploadprogress\_php\_rfc1867\_file的关键代码：

> upload\_id = emalloc(strlen(\*e\_data-&gt;value) + 1);
> 
> strcpy(upload\_id, \*e\_data-&gt;value);
> 
> progress-&gt;upload\_id = upload\_id;
> 
> progress-&gt;time\_last  = time(NULL);
> 
> progress-&gt;speed\_average  = 0;
> 
> progress-&gt;speed\_last     = 0;
> 
> progress-&gt;bytes\_uploaded = read\_bytes;
> 
> progress-&gt;files\_uploaded = 0;
> 
> progress-&gt;est\_sec        = 0;
> 
> progress-&gt;identifier = uploadprogress\_mk\_filename(upload\_id, template);&lt;&lt;&lt;在指定的模板位置放下了临时文件
> 
> progress-&gt;identifier\_tmp = emalloc(strlen( progress-&gt;identifier) + 4);
> 
> sprintf( progress-&gt;identifier\_tmp, “%s.wr”, progress-&gt;identifier );

关于php\_rfc1867\_callback是什么，可以看哥学社另一哥鸟哥的分析 [http://www.laruence.com/2008/11/07/586.html](http://www.laruence.com/2008/11/07/586.html)

**三.总结**

在探测临时文件大小的时候，APC和 uploadprogress其实是大同小异的方法，先记录，再取大小百分比。

关于哥学社：  
[哥学社](http://www.54chen.com/blog-brother "哥学社")是一个自由博客组织，以提高原创技术博客质量，为成员博客增加更有效评论，由来自腾讯、百度、盛大、人人网、新浪、奇虎、TOM等各大企业的哥们共同起草发起。

关于五四陈：  
54chen(陈臻)，人人网分布式存储研究人员，业余时间混迹于各技术组织且乐此不疲。目前关注实施PHP培训。对flex等前端技术有一点研究。  
个人技术站点:[http://www.54chen.com/](http://www.54chen.com/) 。可以通过电子邮件 czhttp@gmail.com 联系到他。

本文提及的文章：

[http://www.php.net/releases/5\_2\_0.php](http://www.php.net/releases/5_2_0.php)

[http://www.ibm.com/developerworks/cn/opensource/os-php-v525/](http://www.ibm.com/developerworks/cn/opensource/os-php-v525/)

[http://www.laruence.com/2008/11/07/586.html](http://www.laruence.com/2008/11/07/586.html)

原创文章如转载，请注明：转载自[五四陈科学院](http://www.54chen.com/)\[[http://www.54chen.com](http://www.54chen.com/)]  
本文链接: [http://www.54chen.com/php-tech/php-upload-progress.html](http://www.54chen.com/php-tech/php-upload-progress.html "PHP上传进度条深度解析")