主頁(yè) > 知識(shí)庫(kù) > PHP使用Session實(shí)現(xiàn)上傳進(jìn)度功能詳解

PHP使用Session實(shí)現(xiàn)上傳進(jìn)度功能詳解

熱門標(biāo)簽:電子圍欄 Linux服務(wù)器 Mysql連接數(shù)設(shè)置 服務(wù)器配置 科大訊飛語(yǔ)音識(shí)別系統(tǒng) 阿里云 銀行業(yè)務(wù) 團(tuán)購(gòu)網(wǎng)站

本文實(shí)例講述了PHP使用Session實(shí)現(xiàn)上傳進(jìn)度功能。分享給大家供大家參考,具體如下:

實(shí)現(xiàn)文件上傳進(jìn)度條基本是依靠JS插件或HTML5的File API來(lái)完成,其實(shí)PHP配合ajax也能實(shí)現(xiàn)此功能。

PHP手冊(cè)對(duì)于session上傳進(jìn)度是這么介紹的:

當(dāng) session.upload_progress.enabled INI 選項(xiàng)開(kāi)啟時(shí),PHP 能夠在每一個(gè)文件上傳時(shí)監(jiān)測(cè)上傳進(jìn)度。 這個(gè)信息對(duì)上傳請(qǐng)求自身并沒(méi)有什么幫助,但在文件上傳時(shí)應(yīng)用可以發(fā)送一個(gè)POST請(qǐng)求到終端(例如通過(guò)XHR)來(lái)檢查這個(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連接在一起的值。 通常這些鍵值可以通過(guò)讀取INI設(shè)置來(lái)獲得,例如

?php
$key = ini_get("session.upload_progress.prefix") . ini_get("session.upload-progress.name");
var_dump($_SESSION[$key]);
?>

通過(guò)將$_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ì)算一次。 通過(guò)合理設(shè)置這兩個(gè)選項(xiàng)的值,這個(gè)功能的開(kāi)銷幾乎可以忽略不計(jì)。

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

下面原理介紹:

  當(dāng)瀏覽器向服務(wù)器端上傳一個(gè)文件時(shí),PHP將會(huì)把此次文件上傳的詳細(xì)信息(如上傳時(shí)間、上傳進(jìn)度等)存儲(chǔ)在session當(dāng)中。然后,隨著上傳的進(jìn)行,周期性的更新session中的信息。這樣,瀏覽器端就可以使用Ajax周期性的請(qǐng)求一個(gè)服務(wù)器端腳本,由該腳本返回session中的進(jìn)度信息;瀏覽器端的Javascript即可根據(jù)這些信息顯示/更新進(jìn)度條了。

php.ini需配置以下選項(xiàng)

session.upload_progress.enabled = "1"
session.upload_progress.cleanup = "1"
session.upload_progress.prefix = "upload_progress_"
session.upload_progress.name = "PHP_SESSION_UPLOAD_PROGRESS"
session.upload_progress.freq = "1%"
session.upload_progress.min_freq = "1"

  其中enabled控制upload_progress功能的開(kāi)啟與否,默認(rèn)開(kāi)啟;
  cleanup 則設(shè)置當(dāng)文件上傳的請(qǐng)求提交完成后,是否清除session的相關(guān)信息,默認(rèn)開(kāi)啟,如果需要調(diào)試$_SESSION,則應(yīng)該設(shè)為Off。
  prefix 和 name 兩項(xiàng)用來(lái)設(shè)置進(jìn)度信息在session中存儲(chǔ)的變量名/鍵名。
  freq 和 min_freq 兩項(xiàng)用來(lái)設(shè)置服務(wù)器端對(duì)進(jìn)度信息的更新頻率。合理的設(shè)置這兩項(xiàng)可以減輕服務(wù)器的負(fù)擔(dān)。
  在上傳文件的表單中,需要為該次上傳設(shè)置一個(gè)標(biāo)識(shí)符,并在接下來(lái)的過(guò)程中使用該標(biāo)識(shí)符來(lái)引用進(jìn)度信息。

  具體的,在上傳表單中需要有一個(gè)隱藏的input,它的name屬性為php.ini中 session.upload_progress.name 的值;它的值為一個(gè)由你自己定義的標(biāo)識(shí)符。如下:
 代碼如下:

input type="hidden" name="?php echo ini_get('session.upload_progress.name'); ?>" value="test" />

接到文件上傳的表單后,PHP會(huì)在$_SESSION變量中新建鍵,鍵名是一個(gè)將session.upload_progress.prefix的值與上面自定義的標(biāo)識(shí)符連接后得到的字符串,可以這樣得到:

代碼如下:

$name = ini_get('session.upload_progress.name');
$key = ini_get('session.upload_progress.prefix') . $_POST[$name];
$_SESSION[$key]; // 這里就是此次文件上傳的進(jìn)度信息了
$_SESSION[$key]這個(gè)變量的結(jié)構(gòu)是這樣的:

array (
  'upload_progress_test' => array (
    'start_time' => 1491494993,  // 開(kāi)始時(shí)間
    'content_length' => 1410397, // POST請(qǐng)求的總數(shù)據(jù)長(zhǎng)度
    'bytes_processed' => 1410397, // 已收到的數(shù)據(jù)長(zhǎng)度
    'done' => true,        // 請(qǐng)求是否完成 true表示完成,false未完成
    'files' => array (
      0 => array (
        'field_name' => 'file1',
        'name' => 'test.jpg',
        'tmp_name' => 'D:\\wamp\\tmp\\phpE181.tmp',
        'error' => 0,
        'done' => true,
        'start_time' => 1491494993,
        'bytes_processed' => 1410096,
      ),
    ),
  ),
);

這樣,我們就可以使用其中的 content_length bytes_processed 兩項(xiàng)來(lái)得到進(jìn)度百分比。

原理介紹完了,下面我們來(lái)完整的實(shí)現(xiàn)一個(gè)基于PHP和Javascript的文件上傳進(jìn)度條。

上傳表單index.php

?php session_start(); ?>
!DOCTYPE html>
html lang="zh-CN">
head>
  meta charset="utf-8">
  title>PHP(5.4) Session 上傳進(jìn)度 Demo/title>
  meta name="viewport" content="width=device-width, initial-scale=1.0">
  meta name="keywords" content=""/>
  meta name="description" content=""/>
  meta name="author" content="">
  link  rel="external nofollow" rel="stylesheet">
  style type="text/css">
    body{
      font-size:1em;
      color:#333;
      font-family: "宋體", Arial, sans-serif;
    }
    h1, h2, h3, h4, h5, h6{
      font-family: "宋體", Georgia, serif;
      color:#000;
      line-height:1.8em;
      margin:0;
    }
    h1{ font-size:1.8em; }
    #wrap{
      margin-top:15px;
      margin-bottom:50px;
      background:#fff;
      border-radius:5px;
      box-shadow:inset 0 0 3px #000,
      0 0 3px #eee;
    }
    #header{
      border-radius:5px 5px 0 0;
      box-shadow:inset 0 0 3px #000;
      padding:0 15px;
      color:#fff;
      background: #333333;
    }
    #header h1{
      color:#fff;
    }
    #article{
      padding:0 15px;
    }
    #footer{
      text-align:center;
      border-top:1px solid #ccc;
      border-radius:0 0 5px 5px;
    }
    .progress {
      width: 100%;
      border: 1px solid #4da8fe;
      border-radius: 40px;
      height: 20px;
      position: relative;
    }
    .progress .labels {
      position: relative;
      text-align: center;
    }
    .progress .bar {
      position: absolute;
      left: 0;
      top: 0;
      background: #4D90FE;
      height: 20px;
      line-height:20px;
      border-radius: 40px;
      min-width: 20px;
    }
    .report-file {
      display: block;
      position: relative;
      width: 120px;
      height: 28px;
      overflow: hidden;
      border: 1px solid #428bca;
      background: none repeat scroll 0 0 #428bca;
      color: #fff;
      cursor: pointer;
      text-align: center;
      float: left;
      margin-right:5px;
    }
    .report-file span {
      cursor: pointer;
      display: block;
      line-height: 28px;
    }
    .file-prew {
      cursor: pointer;
      position: absolute;
      top: 0;
      left:0;
      width: 120px;
      height: 30px;
      font-size: 100px;
      opacity: 0;
      filter: alpha(opacity=0);
    }
    .container{
      padding-left:0;
      padding-right:0;
      margin:0 auto;
    }
  /style>
/head>
body>
div id="wrap" class="container">
  div id="header">
    h1>Session上傳進(jìn)度 Demo/h1>
  /div>
  div id="article">
    form id="upload-form" action="upload.php" method="POST" enctype="multipart/form-data" style="margin:15px 0"
       target="hidden_iframe">
      input type="hidden" name="?php echo ini_get("session.upload_progress.name"); ?>" value="test"/>
      div class="report-file">
        span>上傳文件…/span>input tabindex="3" size="3" name="file1" class="file-prew" type="file" onchange="document.getElementById('textName').value=this.value">
      /div>
      input type="text" id="textName" style="height: 28px;border:1px solid #f1f1f1" />
      p>
        input type="submit" class="btn btn-default" value="上傳"/>
      /p>
    /form>
    div id="progress" class="progress" style="margin-bottom:15px;display:none;">
      div class="bar" style="width:0%;">/div>
      div class="labels">0%/div>
    /div>
  /div> !-- #article -->
  div id="footer">
    p> /p>
  /div>
/div>!-- #wrap -->
iframe id="hidden_iframe" name="hidden_iframe" src="about:blank" style="display:none;">/iframe>
script src="https://cdn.bootcss.com/jquery/3.1.1/jquery.min.js">/script>
script type="text/javascript">
  function fetch_progress() {
    $.get('progress.php', {'?php echo ini_get("session.upload_progress.name"); ?>': 'test'}, function (data) {
      var progress = parseInt(data);
      $('#progress .labels').html(progress + '%');
      $('#progress .bar').css('width', progress + '%');
      if (progress  100) {
        setTimeout('fetch_progress()', 500);
      } else {
        $('#progress .labels').html('100%');
      }
    }, 'html');
  }
  $('#upload-form').submit(function () {
    $('#progress').show();
    //圖片比較小,看不出進(jìn)度條加載效果,初始設(shè)33%
    $('#progress .labels').html('33%');
    $('#progress .bar').css('width', '33%');
    setTimeout('fetch_progress()', 500);
  });
/script>
/body>
/html>

  注意表單中的session.upload_progress.name隱藏項(xiàng),值設(shè)置為了test。表單中僅有一個(gè)文件上傳input,如果需要,你可以添加多個(gè)。
  這里需要特別注意一下表單的target屬性,這里設(shè)置指向了一個(gè)當(dāng)前頁(yè)面中的iframe。這一點(diǎn)很關(guān)鍵,通過(guò)設(shè)置target屬性,讓表單提交后的頁(yè)面顯示在iframe中,從而避免當(dāng)前的頁(yè)面跳轉(zhuǎn)。因?yàn)槲覀冞€得在當(dāng)前頁(yè)面顯示進(jìn)度條呢。

上傳文件upload.php

?php
/**
 * 上傳文件
 */
if(is_uploaded_file($_FILES['file1']['tmp_name'])){
  //unlink($_FILES['file1']['tmp_name']);
  $fileName = 'pic_' . date('YmdHis') . mt_rand(10000,99999);
  $ext = substr($_FILES['file1']['name'], strrpos($_FILES['file1']['name'], '.'));
  move_uploaded_file($_FILES['file1']['tmp_name'], $fileName . $ext);
}

ajax獲取上傳進(jìn)度progress.php

?php
/**
 * AJAX獲取上傳文件進(jìn)度
 */
session_start();
$i = ini_get('session.upload_progress.name');
//session.upload_progress.name = "PHP_SESSION_UPLOAD_PROGRESS"
$key = ini_get("session.upload_progress.prefix") . $_GET[$i];
//session.upload_progress.prefix = "upload_progress_" . 'test'
if (!empty($_SESSION[$key])) {
  $current = $_SESSION[$key]["bytes_processed"]; // 已收到的數(shù)據(jù)長(zhǎng)度
  $total  = $_SESSION[$key]["content_length"]; // POST請(qǐng)求的總數(shù)據(jù)長(zhǎng)度
  echo $current  $total ? ceil($current / $total * 100) : 100;
}else{
  echo 100;
}

注意事項(xiàng):

1.input標(biāo)簽的位置name為session.upload_progress.name的input標(biāo)簽一定要放在文件input input type="file" /> 的前面。

2.通過(guò)設(shè)置 $_SESSION[$key]['cancel_upload'] = true 可取消當(dāng)次上傳。但僅能取消正在上傳的文件和尚未開(kāi)始的文件。已經(jīng)上傳成功的文件不會(huì)被刪除。

3.應(yīng)該通過(guò) setTimeout() 來(lái)調(diào)用 fetch_progress(),這樣可以確保一次請(qǐng)求返回之后才開(kāi)始下一次請(qǐng)求。如果使用 setInterval() 則不能保證這一點(diǎn),有可能導(dǎo)致進(jìn)度條出現(xiàn)'不進(jìn)反退'。

更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php文件操作總結(jié)》、《PHP目錄操作技巧匯總》、《PHP常用遍歷算法與技巧總結(jié)》、《PHP數(shù)據(jù)結(jié)構(gòu)與算法教程》、《php程序設(shè)計(jì)算法總結(jié)》及《PHP網(wǎng)絡(luò)編程技巧總結(jié)》

希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。

您可能感興趣的文章:
  • php7 list()、session及其他模塊的修改實(shí)例分析
  • PHP7創(chuàng)建銷毀session的實(shí)例方法
  • PHP 圖像處理與SESSION制作超簡(jiǎn)單驗(yàn)證碼的方法示例
  • PHP 實(shí)現(xiàn)超簡(jiǎn)單的SESSION與COOKIE登錄驗(yàn)證功能示例
  • PHP cookie與session會(huì)話基本用法實(shí)例分析
  • 如何解決PHP獲取不到SESSION信息之一般情況
  • thinkphp 5框架實(shí)現(xiàn)登陸,登出及session登陸狀態(tài)檢測(cè)功能示例
  • php實(shí)現(xiàn)多站點(diǎn)共用session實(shí)現(xiàn)單點(diǎn)登錄的方法詳解
  • PHP實(shí)現(xiàn)cookie跨域session共享的方法分析
  • PHP SESSION跨頁(yè)面?zhèn)鬟f失敗解決方案

標(biāo)簽:廣元 蚌埠 江蘇 萍鄉(xiāng) 大理 衢州 衡水 棗莊

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《PHP使用Session實(shí)現(xiàn)上傳進(jìn)度功能詳解》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266