Session 上傳進(jìn)度

注意: 此特性自 PHP 5.4.0 后可用。

當(dāng) session.upload_progress.enabled INI 選項(xiàng)開啟時(shí),PHP 能夠在每一個(gè)文件上傳時(shí)監(jiān)測(cè)上傳進(jìn)度。 這個(gè)信息對(duì)上傳請(qǐng)求自身并沒有什么幫助,但在文件上傳時(shí)應(yīng)用可以發(fā)送一個(gè)POST請(qǐng)求到終端(例如通過XHR)來檢查這個(gè)狀態(tài)

當(dāng)一個(gè)上傳在處理中,同時(shí)POST一個(gè)與INI中設(shè)置的session.upload_progress.name同名變量時(shí),上傳進(jìn)度可以在$_SESSION中獲得。 當(dāng)PHP檢測(cè)到這種POST請(qǐng)求時(shí),它會(huì)在$_SESSION中添加一組數(shù)據(jù), 索引是 session.upload_progress.prefixsession.upload_progress.name連接在一起的值。 通常這些鍵值可以通過讀取INI設(shè)置來獲得,例如

<?php
$key 
ini_get("session.upload_progress.prefix") . ini_get("session.upload_progress.name");
var_dump($_SESSION[$key]);
?>

通過將$_SESSION[$key]["cancel_upload"]設(shè)置為true,還可以取消一個(gè)正在處理中的文件上傳。 當(dāng)在同一個(gè)請(qǐng)求中上傳多個(gè)文件,它僅會(huì)取消當(dāng)前正在處理的文件上傳和未處理的文件上傳,但是不會(huì)移除那些已經(jīng)完成的上傳。 當(dāng)一個(gè)上傳請(qǐng)求被這么取消時(shí),$_FILES中的error將會(huì)被設(shè)置為 UPLOAD_ERR_EXTENSION。

session.upload_progress.freqsession.upload_progress.min_freq INI選項(xiàng)控制了上傳進(jìn)度信息應(yīng)該多久被重新計(jì)算一次。 通過合理設(shè)置這兩個(gè)選項(xiàng)的值,這個(gè)功能的開銷幾乎可以忽略不計(jì)。

示例 #1 樣例信息

一個(gè)上傳進(jìn)度數(shù)組的結(jié)構(gòu)的例子

<form action="upload.php" method="POST" enctype="multipart/form-data">
 <input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="123" />
 <input type="file" name="file1" />
 <input type="file" name="file2" />
 <input type="submit" />
</form>

在session中存放的數(shù)據(jù)看上去是這樣子的:

<?php
$_SESSION
["upload_progress_123"] = array(
 
"start_time" => 1234567890,   // The request time
 
"content_length" => 57343257// POST content length
 
"bytes_processed" => 453489,  // Amount of bytes received and processed
 
"done" => false,              // true when the POST handler has finished, successfully or not
 
"files" => array(
  
=> array(
   
"field_name" => "file1",       // Name of the <input/> field
   // The following 3 elements equals those in $_FILES
   
"name" => "foo.avi",
   
"tmp_name" => "/tmp/phpxxxxxx",
   
"error" => 0,
   
"done" => true,                // True when the POST handler has finished handling this file
   
"start_time" => 1234567890,    // When this file has started to be processed
   
"bytes_processed" => 57343250// Amount of bytes received and processed for this file
  
),
  
// An other file, not finished uploading, in the same request
  
=> array(
   
"field_name" => "file2",
   
"name" => "bar.avi",
   
"tmp_name" => NULL,
   
"error" => 0,
   
"done" => false,
   
"start_time" => 1234567899,
   
"bytes_processed" => 54554,
  ),
 )
);

警告

為了使這個(gè)正常工作,web服務(wù)器的請(qǐng)求緩沖區(qū)需要禁用,否則 PHP可能僅當(dāng)文件完全上傳完成時(shí)才能收到文件上傳請(qǐng)求。 已知會(huì)緩沖這種大請(qǐng)求的程序有Nginx。

警告

這個(gè)進(jìn)度信息是在任意腳本被執(zhí)行前寫入session的,因此通過 ini_set()session_name()修改session名將會(huì)導(dǎo)致一個(gè)沒有上傳進(jìn)度信息的session。