


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
}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 + '%');
}else{
$('#progress .label').html('Done!');
}
}, 'html');
}
$('#upload-form').submit(function(){
$('#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 .
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'.

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.


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

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use

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