PHP File upload progress bar based on session and JavaScript implementation _php Tutorial

Source: Internet
Author: User
Tags file upload progress bar php file upload
If you are using php5.4 before can only be achieved through ajax,iframe or some other means, if you are using php5.4 we can use the session.upload_progress to quickly combine JS implementation file upload progress bar.


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)

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:


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:

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

$_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 (...),
)
So that 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.

The code warehouse for this example: github:pureweber/samples/php-upload-progress

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



0%
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.

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:

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

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 See: Github:pureweber/samples/php-upload-progress

Precautions
The location of the input label
The input tag for name Session.upload_progress.name must be placed in the file inputThe front.

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

http://www.bkjia.com/PHPjc/632766.html www.bkjia.com true http://www.bkjia.com/PHPjc/632766.html techarticle If you are using php5.4 before can only be achieved through ajax,iframe or some other means, if you are using php5.4 we can use the session.upload_progress to quickly combine JS real ...

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