PHP Session and Javascript file Upload progress bar

Source: Internet
Author: User
Tags apc file upload file upload progress bar php session php and setinterval

Before PHP 5.4, it was not easy to implement such a progress bar. There are three main methods:

1. Use Flash, Java, ActiveX
2. Use php apc extension
3. Use the HTML5 File API
The first method relies on third-party browser plug-ins, which are not universally available and may cause security risks. However, because Flash is widely used, many websites still use Flash as a solution.

The disadvantage of the second method is that it needs to install the php apc extension library and requires the user to be able to control the server configuration. In addition, if the installation of APC is only for the purpose of implementing an upload progress bar, it is obviously a bit cool.

The third method should be the most ideal method. You only need to use Javascript on the browser without server support. However, because HTML5 standards have not yet been established and the support of browser vendors is also different, this method is still difficult to popularize.

The session-based Upload progress monitoring function (session. upload_progress) introduced in PHP 5.4 provides a server-side Upload progress monitoring solution. After upgrading to PHP 5.4, you do not need to install the APC extension. You can only use native PHP and front-end Javascript to implement the upload progress bar.

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

Principles
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)

The code is as follows: Copy code

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 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. upload_progress.name; its value is an identifier defined by you. As follows:

The code is as follows: Copy code
<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. 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:

The code is as follows: Copy code

$ Name = ini_get ('session. upload_progress.name ');
$ 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:

The code is as follows: Copy code

<? Php
$ _ 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.

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

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

The code is as follows: Copy code

<Form id = "upload-form"
Action = "upload. php" method = "POST" enctype = "multipart/form-data"
Style = "margin: 15 p x 0" target = "hidden_iframe">
 
<Input type = "hidden" name = "<? Php echo ini_get ("session. upload_progress.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 that the session. upload_progress.name 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.

# The div SS div 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.

The code is as follows: Copy code

<? Php
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:

The code is as follows: Copy code

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

The code is as follows: Copy code
Function fetch_progress (){
$. Get ('progress. Php', {'<? Php echo ini_get ("session. upload_progress.name");?> ': '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! '


Notes


Input tag location
The input tag whose name is session. upload_progress.name must be placed before the input <input type = "file"/> file.

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

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.