文件上傳進度反饋, 這個需求在當前是越來越普遍, 比如大附件郵件. 在PHP5.4以前, 我們可以通過APC提供的功能來實現. 或者使用PECL擴展uploadprogress來實現.
雖然說, 它們能很好的解決現在的問題, 但是也有很明顯的不足:
- 1. 他們都需要額外安裝(我們並沒有打算把APC加入PHP5.4)
- 2. 它們都使用本地機制來存儲這些信息, APC使用共享內存, 而uploadprogress使用文件系統(不考慮NFS), 這在多臺前端機的時候會造成麻煩.
從PHP的角度來說, 最好的儲存這些信息的地方應該是SESSION, 首先它是PHP原生支持的機制. 其次, 它可以被配置到存放到任何地方(支持多機共享).
正因爲此, Arnaud Le Blanc提出了針對Session報告上傳進度的RFC, 並且現在實現也已經包含在了PHP5.4的主幹中.
這個新特性, 提供了一些新的INI配置, 他們和APC的相關配置很類似:
- session.upload_progress.enabled[=1] : 是否啓用上傳進度報告(默認開啓)
- session.upload_progress.cleanup[=1] : 是否在上傳完成後及時刪除進度數據(默認開啓, 推薦開啓).
- session.upload_progress.prefix[=upload_progress_] : 進度數據將存儲在_SESSION[session.upload_progress.prefix . _POST[session.upload_progress.name]]
- session.upload_progress.name[=PHP_SESSION_UPLOAD_PROGRESS] : 如果_POST[session.upload_progress.name]沒有被設置, 則不會報告進度.
- session.upload_progress.freq[=1%] : 更新進度的頻率(已經處理的字節數), 也支持百分比表示’%’.
- session.upload_progress.min_freq[=1.0] : 更新進度的時間間隔(秒級)
對於如下的上傳表單:
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="hidden"
name="<?php echo ini_get("session.upload_progress.name"); ?>" value="laruence" />
<input type="file" name="file1" />
<input type="file" name="file2" />
<input type="submit" />
</form>
如果我們上傳一個足夠大的文件(網速要是足夠慢就更好:P), 我們就可以從_SESSION中, 得到類似下面的進度信息:$_SESSION["upload_progress_laruence"] = array(
"start_time" => 1234567890, // 請求時間
"content_length" => 57343257, // 上傳文件總大小
"bytes_processed" => 453489, // 已經處理的大小
"done" => false, // 當所有上傳處理完成後爲TRUE
"files" => array(
0 => array(
"field_name" => "file1", // 表單中上傳框的名字
// The following 3 elements equals those in $_FILES
"name" => "foo.avi",
"tmp_name" => "/tmp/phpxxxxxx",
"error" => 0,
"done" => true, // 當這個文件處理完成後會變成TRUE
"start_time" => 1234567890, // 這個文件開始處理時間
"bytes_processed" => 57343250, // 這個文件已經處理的大小
),
// An other file, not finished uploading, in the same request
1 => array(
"field_name" => "file2",
"name" => "bar.avi",
"tmp_name" => NULL,
"error" => 0,
"done" => false,
"start_time" => 1234567899,
"bytes_processed" => 54554,
),
)
);
這個是不是很方便呢?
但是還是要提醒一下, PHP 5.4還處於開發階段, 在最終release之前, 任何新特性都可能被調整或者更改. 如果大家有任何建議, 也歡迎反饋, 幫助我們使得PHP變得更好.
謝謝
Johannes的blog也介紹過: http://schlueters.de/blog/archives/151-Upload-Progress-in-PHP-trunk.html
更多更新信息, 請關注: Changelog
本文轉載自: http://www.laruence.com/2011/10/10/2217.html