PHP Get File Upload progress

Source: Internet
Author: User

There are many ways to get the file upload progress, this article is about using session.upload_progress, based on the PHP 5.4 version of the method.

"1" File php.ini configuration

Set according to the actual situation

Session.upload_progress.enabled[=1]: Whether to enable upload progress report (default on)
Session.upload_progress.cleanup[=1]: Whether to delete the progress data in time after the upload is complete (default on, recommended to open).
Session.upload_progress.prefix[=upload_progress_]: Progress data will be stored in _session[session.upload_progress.prefix. _POST[ Session.upload_progress.name]]
Session.upload_progress.name[=php_session_upload_progress]: If _post[session.upload_progress.name] is not set, progress will not be reported.
session.upload_progress.freq[=1%]: The frequency of the update progress (number of bytes already processed), and the percent '% ' is also supported.
SESSION.UPLOAD_PROGRESS.MIN_FREQ[=1.0]: Time interval for update progress (seconds)


Allows the client to send a single post request with the maximum data M
post_max_size=2048m

; Accept all data to the maximum time to start executing the script S
Max_input_time=60

The maximum execution time of the script S
Max_execution_time=0

, whether to turn on file upload function
File_uploads = On

; temp directory for file uploads
Upload_tmp_dir= "C:\xampp\tmp"

Allow a single request to upload the maximum file size M
Upload_max_filesize = 2048M

Allow a single post request to upload the maximum number of files simultaneously
Max_file_uploads = 20




Introduction to the "2" _files variable

$_files["File" ["Name"]-the name of the uploaded file $_files["file" ["type"]-the type of the file being uploaded $_files["file" ["Size"]-the size of the uploaded file, in bytes $_files[" File "[" Tmp_name "]-the name of the temporary copy of the file stored on the server $_files[" file "[" Error "]-error code caused by file upload


"3" code

File Upload Form

Set the value of Session.upload_progress.name key

<?phpif (Version_compare (Phpversion (), ' 5.4.0 ', ' < ') exit (' Error:your PHP version is '. Phpversion (). ' But this script requires PHP 5.4.0 or higher. '); if (!intval (Ini_get (' session.upload_progress.enabled '))) exit (' session.upload_progress.enabled is not enabled, Please activate it in the Your PHP config file to use the this script. Require_once ("upload.class.php");? ><!doctype html>

File Upload processing class

<?phpclass cupload{Const Upload_progress_prefix = ' Progress_bar ';    Private $_smsg, $_suploaddir, $_sprogresskey; The short array syntax (only for PHP 5.4.0 and higher) private $_aerrfile = [UPLOAD_ERR_OK = ' T Here are no error, the file uploaded with success. ', Upload_err_ini_size = ' The uploaded file exceeds the UPL oad_max_filesize directive in php.ini. ', upload_err_form_size = ' The uploaded file exceeds the Max_file_size  directive that is specified in the HTML form. ', upload_err_partial = ' The uploaded file was only partially Uploaded. ', Upload_err_no_file = ' NO FILE was uploaded. ', Upload_err_no_tmp_dir = ' Missing a t Emporary folder. ', Upload_err_cant_write = ' Failed to WRITE file to disk. ', Upload_err_extension =&gt ;    ' A PHP extension stopped the file upload. '    ]; Public Function __construct () {//Session initialization if (' = = = = session_id ()) session_start ();        $this->_suploaddir = ' uploads/';    $this->_sprogresskey = Strtolower (Ini_get (' Session.upload_progress.prefix '). Static::upload_progress_prefix);               Public Function __destruct () {if ('!== session_id ()) {$_session = array ();        Session_destroy ();            }}/** * @return Object this */Public function AddFile () {if (!empty ($_files)) {            $this->_smsg = "; foreach ($_files as $sKey + $aFiles) {for ($i = 0, $iNumFiles = count ($aFiles [' tmp_name ']); $ i < $iNumFiles; $i + +) {/** * Get parameters for uploading files */$i                    Errcode = $aFiles [' ERROR '] [$i];                    $iSize = $aFiles [' Size '] [$i];                    $sFileName = $aFiles [' name '] [$i];                   $sTmpFile = $aFiles [' Tmp_name '] [$i]; $sFileDest = $this->_suploaddir.                    $sFileName;                    $sTypeFile = $aFiles [' type '] [$i]; /** * Detection File type *//$bIsImgExt = (Strtolower (substr (STRRCHR ($sFil ename, '. '), 1)); Get the file extension//if (($bIsImgExt = = ' jpeg ' | | $bIsImgExt = = ' jpg ' | | $bIsImgExt = = ' png ' | | Bisimgext = = ' gif ') && (strstr ($sTypeFile, '/', true) = = = ' Image ') {if                        ($iErrCode = = UPLOAD_ERR_OK)                                                        {Move_uploaded_file ($sTmpFile, $sFileDest); $this->_smsg. = ' <p style= ' color:green; Font-weight:bold; Text-align:center ">successful". $sFileName.                            ' File Upload!</p> '; $this->_smsg. = ' <p style= ' text-align:center ' >image type: '. Str_replace (' image/', ', $sTypeFile).                ' <br/> ';            $this->_smsg. = ' Size: '. Round ($iSize/1024).                            ' Kb<br/> '; $this->_smsg. = ' <a href= '. $sFileDest. ' Title= ' Click here for see the original file "target=" _blank "></a></p>"; } else {$this->_smsg. = ' <p style= ' color:r Ed Font-weight:bold; Text-align:center ">error while downloading the file" '. $sFileName.                            ' <br/> '; $this->_smsg. = ' Error code: '. $iErrCode.                            ' <br/> '; $this->_smsg. = ' Error message: '. $this->_aerrfile[$iErrCode].                        ' </p> '; }}//else {//$this->_smsg. = ' <p s TYle= "color:red; Font-weight:bold; Text-align:center ">file type incompatible.                    Please save the image in. jpg,. jpeg,. png or .gif</p> '; }}}}} else {$this->_smsg = ' <p style= ' color:red; font-w Eight:bold;        Text-align:center ">you must select at least one file before submitting the form.</p> ';    } return $this; }/** * Interrupt file Upload * * @return Object this */Public function cancel () {if (!empty ($_sessi        on[$this->_sprogresskey])) $_session[$this->_sprogresskey][' cancel_upload '] = true;    return $this; }/** * @return upload progress */Public Function progress () {if (!empty ($_session[$this->_sprogress            Key]) {$aData = $_session[$this->_sprogresskey];            $iProcessed = $aData [' bytes_processed '];            $iLength = $aData [' content_length ']; $iProgress = ceil (100* $iProcessed/$iLength);        } else {$iProgress = 100;    } return $iProgress;         }/** * @return Object this */Public function Show () {Ob_start ();         Echo ' <p><strong>$_files result:</strong></p><pre> ';         Var_dump ($_files);         Echo ' </pre> ';         Echo ' <p><strong>$_session result:</strong></p><pre> ';         Var_dump ($_session);         Echo ' </pre> ';         $this->_smsg = Ob_get_clean ();     return $this;     }/** * Get the JSON informational message.     * * @param integer $iStatus, 1 = success, 0 = error * @param string $sTxt * @return string JSON Format. */public static function Jsonmsg ($iStatus, $sTxt) {return ' {' status ': '. $iStatus. ', ' txt ': '. $sTxt.     '"}';     }/** * Get the informational message. * * @return String */Public Function __ToString () {return $this->_smsg; }}

Perform file upload operations

<?phprequire_once ("upload.class.php"); $upload = new Cupload; $upload->addfile (); Echo $upload;/*$_session["  Upload_progress_testupload "] = Array (" start_time "= 1234567890,//Request Time" content_length "= 57343257,//upload total file size "Bytes_processed" = 453489,//the size that has been processed "done" = = false,//when all upload processing is completed is true "files" = = Array (0 = > Array ("field_name" = "file1",//The name of the upload box in the form//the following 3 elements equals those in $_files "name "= =" Foo.avi "," tmp_name "="/tmp/phpxxxxxx "," error "= 0," Done "= true,//When this file is processed Tighten will become true "start_time" = 1234567890,//This file starts processing time "bytes_processed" = 57343250,//The size of this file has been processed),//an Other file, not finished uploading, in the same request 1 = = Array ("Field_name" and "File2", "name" = "Bar". Avi "," tmp_name "= NULL," error "= 0," done "and" = False, "start_time" = 1234567899, "Bytes_processe D "= 54554,),);*/?>
get File Upload Progress

<?phpsession_start (); Require_once ("upload.class.php"); Echo (new Cupload ())->progress ();? >


Copyright NOTICE: This article is the original article of Bo-Lang's work room, without the permission of Bo Master not to reprint.

PHP Get File Upload progress

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.