Php file Upload progress bar is implemented based on Session and Javascript

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


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)

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:

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

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

$ _ 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:

<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 = "" 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> pay attention to the hidden items of session. upload_progress.name in the form, and set the value 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.

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

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

Done!

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

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

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.