PHP Upload progress bar-apc

Source: Internet
Author: User
Tags apc php upload progress bar
Instructions for usePHP v5.2 adds a hook for developers to track File Upload progress in real time. If the correct library is installed and configured, the new "Hook" in PHP v5.2 is actually a data point that can be obtained during file transfer. These new hooks use a function called alternative PHP cache. When the PHP script receives an uploaded file, the interpreter automatically checks $_POST arrayTo find the hidden field named apc_upload_progress. It will become a cache variable and store information about the upload so that the script can access the uploaded file. By default, APC in PHP v5.2 is not enabled. Since the new hook is part of APC, make sure to install the extension and make it available for the PHP interpreter. This will be done by downloading the php_apc extension file. The APC component can be obtained from here: the http://pecl.php.net/package/apc opens <wamproot>/PHP. ini and Adds code lines apc.rfc1867 = on(Can be added to any location ). If you want to test locally and upload large files to see the progress, add the following command: apc.max_file_size = 200M, upload_max_filesize = 200MAnd post_max_size = 200M.

Accounts that can receive files

To receive files, you must first set the form for receiving files. It is very convenient that HTML comes with the standard field type of the file. Like all HTML form fields, it is logically named as typefile. By default, the convenience shown on the right of the block is included.BrowseButton.

Listing 1. HTML form of upload. php
                <?php   $id = $_GET['id'];?><form enctype="multipart/form-data" id="upload_form"       action="target.php" method="POST"><input type="hidden" name="APC_UPLOAD_PROGRESS"        id="progress_key"  value="<?php echo $id?>"/><input type="file" id="test_file" name="test_file"/><br/><input onclick="window.parent.startProgress(); return true;" type="submit" value="Upload!"/></form>

You need to create a PHP page for this form because you need to use a unique key to track uploads. Finally, it will be used to call this pageGETValue. This number will be the value of the APC cache entry key to be retrieved later. To pass this value, the form field must have a hidden field with a special name, so that APC knows that it needs to save the file upload status. This field is called APC_UPLOAD_PROGRESS. This is the hook for starting the cache process. To ensure that PHP can access the correct entries in the cache, we use the retrieved unique ID as the value of the hidden field to create the key for this value. After the user submits the form-we will briefly process the submit button-the browser will use the file and key asPOSTSend part of the data.

After it is loaded into the browser, this page should provide a very simple form, as shown in 1:

Figure 1. Upload a form

To enable users to submit files without re-loading the entire page, you need to embed this form into another fileiframe. If you try to retrieve data only by using the form operation page (target. php), you cannot see any cache information, because the page will not return any information before the upload is complete. For this reason, the most common examples of using this new hook are written in Ajax. By using this method, you can submit a form and check the upload status in the same window without refreshing.

To run the script, you need to continue to an include page, which will setiframeAnd receive the information of the uploaded file. You also need to use a set of JavaScript Functions to obtain data for the Progress indicator and display the progress indicator.



Capture received files

When a file is included in the submission form, the file will be sent to the temporary location of the server until it is saved to the permanent location. When it is on a temporary storage device, you can$_FILESJoin the array to obtain it. You can select a path and save these functions to the server by using the standard file upload function that comes with PHP, or process these functions as needed.

Listing 2. target. php file
                <?php  if($_SERVER['REQUEST_METHOD']=='POST') {  move_uploaded_file($_FILES["test_file"]["tmp_name"],   "c:\\sw\\wamp\\www\\" . $_FILES["test_file"]["name"]);  echo "<p>File uploaded.  Thank you!</p>";}?>

First, viewPOSTWhether the variable has been set and indicates that we have received the form data. If you receive form data and want to include files, you should also have a global array.$_FILES. Move uploaded files to a secure location, depending on the operations you need to take. In this example, you only need to move the file to \ sw \ wamp \ www (of course, this is completely arbitrary. Select a desired location ). After completing this operation, we would like to thank you.

The actual file processing is mainly used to achieve integrity. As this article describes the progress bar, it does not matter how to handle the actual file after it is received.



Progress bar

A script is also required to return the actual upload progress. Listing 3 shows a very simple version.

Listing 3. getprogress. php file
                <?phpif(isset($_GET['progress_key'])) {  $status = apc_fetch('upload_'.$_GET['progress_key']);  echo $status['current']/$status['total']*100;}?>

This script will first look for progress_key, Which is previously discussed$idValue (do not worry, you will immediately see its source ). This will cause the call to return data from the APC Cacheapc_fetch(). We need the correct file information, so we need a unique ID, which is expressed$_GET['progress_key']. CallUpload_xxxxxxParameterapc_fetch(), WhereXxxxxxIs a unique ID; PHP will automatically pre-append upload _ part.

After obtaining the data, you can use JSON extension to set a format that is easier to use in JavaScript and return the entire object (if needed ).$statusAn object is an array with the following fields:

total
Total File Size
current
Number of files received so far
rate
Upload speed (in bytes per second)
filename
File Name
name
Variable name
temp_filename
Location where PHP saves temporary copies of Files
cancel_upload
Whether the upload is canceled (1) or not (0)
done
Upload completed (1) or not completed (0)

In this example, you only need to complete the percentage. You can choose to use more information in your application.



JavaScript showing the progress bar

Now you are ready to start building the actual progress bar. For simplicity, the script uses CSS to create a div that simulates the progress bar and can be controlled using JavaScript, as shown in Listing 4:

Listing 4. Master File progress. php
                

This page contains two nesteddivElement, the one outside is used as the border. The script will adjust the internaldivThe size relative to the border to display the progress. When you clickStart me up!Text,startProgress()The script will callfire()Function. This function checks the counter value. If the value does not exceed 100divSet as externaldivThe percentage value of the width. Then it increases the counter value and tells the browser to execute all the above processes every 10 seconds.

The result will be very similar to Figure 2:

Figure 2. progress bar script

Now, you only need a method to obtain the script to update the width. The width is not an arbitrary number but a percentage of completion.



Integration

The rest is to hook all the content together. You can perform this operation on the progress. php page.

Listing 5. Final progress. php page
                <?php   $id = uniqid("");?>

Starting from the underlying layer, we have added the upload. php script embedded in Listing 1.iframeTo provide a unique ID generated at the top of the page.

Do you still rememberSubmitButton?

<input onclick="window.parent.startProgress(); return true;" type="submit" value="Upload!"/>

This button completes two tasks. Submit a form, like a normalSubmitButton, but it will be called in the main window before the operation is executed.startProgress()Script.startProgress()The script will tell the progress bar to display itself-no display attribute at the beginning, and then tell the browser to wait for a second and then executegetProgress()Script.

Now,getProgress()Scripts make things interesting. Do you remember that I mentioned earlier that I would need to use Ajax or a similar method to check the file progress? In this example, the form uses shortcuts to callGdownloadUrl()Function (note that the form will be imported to the library at the top of the page. You will need to obtain your own accesskey for accessing this database, but it is free from Google ).

This function downloads the URL content -- in this example, the getprogress. php script -- and runs the anonymous function defined in it. The first parameter accepted by the function is the data returned from the URL. In this example, the percentage is used to update the progress bar. Finally, if the file has not been downloaded, tell the browser to retry every tenth of a second (in actual situations, these calls may not be executed so quickly, but the browser will do its best ).

The final result is that the page allows the user to view the progress of the file being uploaded.

Figure 3. Output of Progress. php
 

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.