PHP Upload file progress bar

Source: Internet
Author: User
Tags apc file upload progress bar

PS: This article goes from the script home

The ability to upload files is often required in a Web application. Typical scenarios include user Avatar uploads, photo album uploads, and more. When you need to upload a larger file, it is necessary to provide a progress bar showing the upload progress.

Before PHP 5.4, it was not easy to implement such a progress bar, there are three main ways:

1. Using Flash, Java, ActiveX
2. Using the APC extension for PHP
3. Using the HTML5 file API

The first method relies on third-party browser plug-ins, which are less versatile and prone to security risks. However, because of the wide use of flash, there are many sites using flash as a solution.

The disadvantage of the second approach is that it requires the installation of the APC extension library for PHP, which requires the user to be able to control the server-side configuration. In addition, if you install APC just to implement an upload progress bar, then obviously a bit overkill meaning.

The third approach should be the best approach, without server-side support, using JavaScript only on the browser side. However, due to the HTML5 standard has not been established, the support of the browser vendors are not the same, so temporarily this method is still difficult to popularize.

The session-based Upload progress monitoring feature (session.upload_progress) introduced in PHP 5.4 provides a server-side upload progress monitoring solution. After upgrading to PHP 5.4, you can implement the upload progress bar without having to install APC extensions, using only native PHP and front-end JavaScript.

Let's take a look at this new session.upload_progress feature of PHP 5.4 in detail.

Principle Introduction

When the browser uploads a file to the server, PHP will store the details of the file upload (such as upload time, upload progress, etc.) in the session. Then, as the upload progresses, the information in the session is updated periodically. In this way, the browser can use Ajax to periodically request a server-side script that returns progress information from the session, and the browser-side JavaScript will be able to display/update the progress bar based on that information.

So, how is the file upload information stored specifically? How do we access it? Let us explain in detail below.

Some configuration items were introduced in PHP 5.4 (set in php.ini)

Copy CodeThe code is as follows:
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"

Where the enabled control Upload_progress function is turned on or off, the cleanup is set when the file upload request is completed, whether to clear the session of the relevant information, the default is turned on.

The prefix and name two entries are used to set the variable name/key name stored in the session for progress information. The detailed use of these two items is shown below.

The Freq and min_freq two items are used to set the server-side update frequency for progress information. A reasonable set of these two items can reduce the burden on the server.

In the form where the file is uploaded, you need to set an identifier for the upload and use that identifier in the next procedure to refer to the progress information. Specifically, you need to have a hidden input in the upload form whose Name property is the value of session.upload_progress.name in php.ini; its value is an identifier defined by yourself. As follows:

Copy CodeThe code is as follows:
<input type= "hidden"
Name= "<?php Echo ini_get (' Session.upload_progress.name ');?>"
value= "Test"/>

After receiving the file Upload form, PHP creates a new key in the $_session variable, which is a string that will be obtained after connecting the value of Session.upload_progress.prefix with the identifier you have customized above, which can be obtained as follows:

Copy CodeThe code is as follows:
$name = Ini_get (' Session.upload_progress.name ');
$key = Ini_get (' Session.upload_progress.prefix '). $_post[$name];

$_session[$key]; This is the progress information of this file upload.


$_session[$key] The structure of this variable is this:

Copy CodeThe code is as follows:
$_session["upload_progress_test"] = Array (
"Start_time" = 1234567890,//Start time
"Content_length" = Total data length of 57343257,//POST request
"Bytes_processed" = 453489,//Received data length
"Done" = false,//request completed TRUE indicates complete, false not completed

Information for individual files
"Files" = = Array (
0 = = Array (...),
Multiple files can be included in the same request
1 = = Array (...),
)
);

In this way, we can use the Content_length and bytes_processed two items to get the progress percentage.

Sample Program

After the introduction of the principle, we will complete the implementation of a PHP and JavaScript-based file upload progress bar.

Upload Form

First of all, to write our upload form page index.php, the code is as follows:

Copy CodeThe code is as follows:
<form id= "Upload-form"
action= "upload.php" method= "POST" enctype= "Multipart/form-data"
Style= "margin:15px 0" target= "hidden_iframe" >

<input type= "hidden" name= "" value= "test"/>
<p><input type= "File" Name= "File1"/></p>
<p><input type= "Submit" value= "Upload"/></p>
</form>

<iframe id= "Hidden_iframe" name= "Hidden_iframe" src= "About:blank" style= "Display:none;" ></iframe>

<div id= "Progress" class= "Progress" style= "Margin-bottom:15px;display:none;" >
<div class= "Bar" style= "width:0%;" ></div>
<div class= "label" >0%</div>
</div>

Note the Session.upload_progress.name hidden item in the form, and the value is set to test. There is only one file upload input in the form, and you can add multiple if necessary.

Here, you need to pay particular attention to the target property of the form, which is set to an IFRAME in the current page. This is critical to avoid the current page jumps by setting the target property so that the page after the form is submitted is displayed in the IFRAME. Because we still have to show the progress bar on the current page.

#progress This div is used to show the progress bar.

Be careful not to forget to add session_start () at the very beginning of index.php.

Working with uploaded files

The action of the form points to upload.php, and we process the uploaded file in upload.php and dump it into the current directory. There is no difference between the upload processing and the usual situation.

Copy CodeThe code is as follows:
if (Is_uploaded_file ($_files[' file1 ' [' tmp_name '])) {
Move_uploaded_file ($_files[' file1 ' [' Tmp_name '], "./{$_files[' file1 ' [' Name ']}");
}
?>

Ajax Get Progress Information

This step is the key, we need to create a progress.php file to read the progress information in the session; We then add JavaScript code to the index.php, initiate an AJAX request to progress.php, and update the progress bar based on the progress information obtained.

The code for progress.php is as follows:

Copy CodeThe code is as follows:
Session_Start ();

$i = Ini_get (' Session.upload_progress.name ');

$key = Ini_get ("Session.upload_progress.prefix"). $_get[$i];

if (!empty ($_session[$key])) {
$current = $_session[$key] ["bytes_processed"];
$total = $_session[$key] ["content_length"];
echo $current < $total? Ceil ($current/$total * 100): 100;
}else{
Echo 100;
}
?>


Here we get the progress information in the $_session variable and then output a progress percentage.

In index.php, we add the following code to the bottom of the page (for simplicity, jquery is used here):

Copy CodeThe code is as follows:
function fetch_progress () {
$.get (' progress.php ', {': ' Test '}, function (data) {
var progress = parseint (data);

$ (' #progress. Label '). HTML (progress + '% ');
$ (' #progress. Bar '). CSS (' width ', progress + '% ');

if (Progress < 100) {
SetTimeout (' fetch_progress () ', 100);
}else{
$ (' #progress. Label '). HTML (' Done! ');
}
}, ' html ');
}

$ (' #upload-form '). Submit (function () {
$ (' #progress '). Show ();
SetTimeout (' fetch_progress () ', 100);
});


When #upload-form is submitted, we display the progress bar, then repeatedly call Fetch_progress () to get the progress information and update the progress bar until the file is uploaded, showing ' Done! '.

done!

Full code Download: Http://xiazai.jb51.net/201410/tools/samples-master.rar

Precautions

The location of the input label

The input tag for name Session.upload_progress.name must be placed in front of the file input <input type= "file"/>.

Cancel Upload

By setting $_session[$key [' cancel_upload '] = True to cancel the upload at the time. However, only files that are being uploaded and files that have not yet started can be canceled. Files that have been successfully uploaded will not be deleted.

SetTimeout vs. SetInterval

Fetch_progress () should be called through SetTimeout (), which ensures that the next request is not started until the request is returned. If you use SetInterval () there is no guarantee that this will cause the progress bar to ' fail back '.

PHP Upload file progress bar

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.