PHP file Upload progress bar based on Session and Javascript implementation _ PHP Tutorial

Source: Internet
Author: User
Tags file upload progress bar
The PHP file Upload progress bar is implemented based on Session and Javascript. If you are using php5.4, you can only implement it through ajax, iframe, or some other methods. if you are using php5.4, we can use session. upload_progress can be quickly combined with js. if you are using php5.4, you can only implement it through ajax, iframe, or some other methods. if you are using php5.4, we can use session. upload_progress can be used in combination with js to quickly implement a file Upload progress bar.

Next we will introduce in detail the new session. upload_progress of PHP 5.4.

When the browser uploads a file to the server, PHP stores the detailed information (such as the upload time and progress) of the file in the session. Then, the information in the session is updated periodically as the upload progresses. In this way, the browser can use Ajax to periodically request a server script, which returns the progress information in the session. the browser Javascript can display/update the progress bar based on the information.

How is the file upload information stored? How do we access it? The following is a detailed description.

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

Session. upload_progress.enabled = "1"
Session. upload_progress.cleanup = "1"
Session. upload_progress.prefix = "upload_progress _"
Session. upload_progress.freq = "1%"
Session. upload_progress.min_freq = "1"
Enabled controls whether the upload_progress function is enabled by default. cleanup sets whether to clear session information after the file upload request is submitted. it is enabled by default.

Prefix and name are used to set the variable name/key name that the progress information is stored in the session. The detailed use of these two items is described below.

Freq and min_freq are used to set the update frequency of server-side progress information. Reasonable settings can reduce the burden on the server.

In the form of an uploaded file, you need to set an identifier for this upload and use this identifier to reference the progress information in the following process. Specifically, a hidden input is required in the upload form, and its name attribute is php. session in ini.; its value is an identifier defined by you. As follows:

Name =" "
Value = "test"/>
After receiving the file upload form, PHP creates a new key in the $ _ SESSION variable. The key name is a session. the value of upload_progress.prefix is connected with the above custom identifier to obtain the string, as shown in the following code:

$ Name = ini_get ('session. ');
$ Key = ini_get ('session. upload_progress.prefix'). $ _ POST [$ name];

$ _ SESSION [$ key]; // the progress of this file Upload
$ _ SESSION [$ key] the structure of this variable is as follows:

$ _ SESSION ["upload_progress_test"] = array (
"Start_time" => 1234567890, // start time
"Content_length" => 57343257, // The total data length of the POST request
"Bytes_processed" => 453489, // The length of the received data
"Done" => false, // whether the request is completed. true indicates that the request is completed. false indicates that the request is not completed.

// Information of a single file
"Files" => array (
0 => array (...),
// The same request may contain multiple files
1 => array (...),
In this way, we can use content_length and bytes_processed to get the progress percentage.

Program example
After the principles are introduced, we will complete the implementation of a file Upload progress bar based on PHP and Javascript.

Code repository in this example: Github: pureweber/samples/php-upload-progress

Upload form
First, compile index. php on the upload form page. the code is as follows:


Note that the session. hidden item in the form is set to test. There is only one file in the form to upload input. you can add multiple files if needed.

Pay special attention to the target attribute of the form, which points to an iframe on the current page. This is critical. by setting the target attribute, the page after the form is submitted is displayed in iframe to avoid the current page jump. Because we have to display the progress bar on the current page.

# Progress p is used to display the progress bar.

Remember to add session_start () at the beginning of index. php ().

Process uploaded files
The action of the form points to upload. php. we process the uploaded file in upload. php and store it to the current directory. This is no different from normal Upload processing.

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 critical. we need to establish a progress. the php file is used to read the progress information in the session. add Javascript code in php to progress. php initiates an Ajax request and updates the progress bar based on the obtained progress information.

The code for SS. php is as follows:

Session_start ();

$ I = ini_get ('session. ');

$ 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, add the following code to the bottom of the page (for simplicity, jQuery is used here ):

Function fetch_progress (){
$. Get ('progress. php', {'': 'test'}, function (data ){
Var progress = parseInt (data );

$ ('# Progress .label'mirror.html (progress +' % ');
$ ('# Progress .bar').css ('width', progress +' % ');

If (progress <100 ){
SetTimeout ('fetch _ ss () ', 100 );
} Else {
$ ('# Progress .label'finished .html (' finished! ');
}, 'Html ');

$ ('# Upload-form'). submit (function (){
$ ('# SS SS'). show ();
SetTimeout ('fetch _ ss () ', 100 );
When # upload-form is submitted, we display the progress bar, and call fetch_progress () repeatedly to obtain the progress information, and update the progress bar until the file upload is complete! '.


Complete code can be found at: Github: pureweber/samples/php-upload-progress

Input tag location
The input tag whose name is session. must be placed in the file input.

Cancel Upload
You can cancel the current upload by setting $ _ SESSION [$ key] ['cel _ upload'] = true. However, only files being uploaded and files not started can be canceled. Files that have been uploaded are not deleted.

SetTimeout vs. setInterval
You should call fetch_progress () through setTimeout () to ensure that the next request starts only after a request is returned. If setInterval () is used, this cannot be ensured. it may cause the progress bar to be 'unreversed '.

Plugin to quickly integrate with js instances...

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: 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.