


PHP file upload progress bar is implemented based on Session and Javascript_PHP tutorial
If you are using php before 5.4, you can only achieve it through ajax, iframe or some other methods. If you are using php5.4, we can use session.upload_progress to quickly combine with js to implement the file upload progress bar. .
Below we will introduce in detail the new session.upload_progress feature of PHP 5.4.
Principle introduction
When the browser uploads a file to the server, PHP will store the detailed information 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 periodically updated. In this way, the browser can use Ajax to periodically request a server-side script, and the script returns the progress information in the session; the browser-side Javascript can display/update the progress bar based on this information.
So, how is the file upload information stored? How do we access it? Let’s explain in detail below.
Some configuration items have been 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"
Among them, enabled controls whether the upload_progress function is enabled or not, which is enabled by default; cleanup sets whether to clear session-related information after the file upload request is submitted, which is enabled by default.
The prefix and name are used to set the variable name/key name where the progress information is stored in the session. See below for detailed usage of these two items.
freq and min_freq are used to set the frequency of updating progress information on the server side. Properly setting these two items can reduce the load on the server.
In the form for uploading files, you need to set an identifier for this upload and use this identifier to reference progress information in the subsequent process. Specifically, there needs to be a hidden input in the upload form, whose name attribute 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 will create a new key in the $_SESSION variable. The key name is a string obtained by concatenating the value of session.upload_progress.prefix with your custom identifier above. It can be obtained like this:
$name = ini_get('session.upload_progress.name');
$key = ini_get('session.upload_progress.prefix') . $_POST[$name];
$_SESSION[$key]; // Here is the progress information of this file upload
The structure of the variable $_SESSION[$key] is as follows:
$_SESSION["upload_progress_test"] = array(
"start_time" => 1234567890, // Start time
"content_length" => 57343257, //Total data length of POST request
"bytes_processed" => 453489, // Received data length
"Done" = & gt; false, // whether the request is completed, and the False is not completed
// Information about a single file
"files" => array(
0 => array( ... ),
// Multiple files can be included in the same request
1 => array( ... ),
)
);In this way, we can use the two items content_length and bytes_processed to get the progress percentage.
Program Example
Now that the principle has been introduced, let’s completely implement a file upload progress bar based on PHP and Javascript.
Code repository for this sample: Github: pureweber/samples/php-upload-progress
Upload form
First, let’s write our upload form page index.php, the code is as follows:
Style="margin:15px 0" target="hidden_iframe">
Special attention needs to be paid to the target attribute of the form here. The setting here points to an iframe in the current page. This is crucial. By setting the target attribute, the page after the form is submitted is displayed in the iframe, thereby avoiding the current page jump. Because we still have to display the progress bar on the current page.
#progress This div is used to display the progress bar.
Note: Don’t forget 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 transfer it to the current directory. There is no difference from the normal upload processing here.
move_uploaded_file($_FILES['file1']['tmp_name'], "./{$_FILES['file1']['name']}");
}
?>Ajax to get progress information
This step is the key. We need to create a progress.php file to read the progress information in the session; then we add Javascript code to index.php, initiate an Ajax request to progress.php, and then update it based on the obtained progress information. Progress bar.
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.
function fetch_progress(){
$.get('progress.php',{ '' : 'test'}, function(data){
var progress = parseInt(data);
$('#progress .bar').css('width', progress + '%');
setTimeout('fetch_progress()', 100);
}else{
$('#progress .label').html('Done!');
}
}, 'html');
}
$('#progress').show();
setTimeout('fetch_progress()', 100);
});
When the #upload-form is submitted, we display the progress bar, then repeatedly call fetch_progress() to obtain the progress information, and update the progress bar until the file is uploaded and 'Complete!' is displayed.
For the complete code, see: Github: pureweber/samples/php-upload-progress
Notes
The position of the input tag
The input tag with name session.upload_progress.name must be placed in front of the file input .
Cancel upload
The current upload can be canceled by setting $_SESSION[$key]['cancel_upload'] = true. However, only files that are being uploaded and files that have not yet been started can be cancelled. Files that have been successfully uploaded will not be deleted.
fetch_progress() should be called through setTimeout() to ensure that one request returns before starting the next request. If you use setInterval(), this cannot be guaranteed, and it may cause the progress bar to appear 'not forward but backward'.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
