Tag: Cache ons Form form body get file upload progress no ring PHP file upload
File upload needs to note the php.ini file, php.ini too many files, you can use Ctrl+f to search for related configuration items.
Configuration Items |
function Description |
File_uploads |
On to turn on file upload function, off for off |
Post_max_size |
Maximum number of post parameters allowed by the system |
Upload_max_filesize |
Maximum number of uploaded files allowed by the system |
Memory_limit |
Memory usage Limits |
Recommended size : file_size (file size) < Upload_max_filesize < Post_max_size < Memory_limit
Steps to upload files:
First, determine if there is an error code
Error code |
Description |
0 |
Error, you can continue to upload the file for subsequent operations. |
1 |
The maximum limit for uploading files is exceeded, upload_max_filesize = 2M php.ini is set, the default is 2M. Can be modified according to the actual needs of the project |
2 |
exceeds the specified file size, specifying the size limit of the upload file based on the business requirements of the project |
3 |
Only some files are uploaded |
4 |
File not being uploaded |
6 |
Temporary folder not found, may not exist or no permissions |
7 |
File write failure, may be full or no permissions on the disk |
Second, custom judgment is beyond the file size range
When you develop the upload feature. We as developers, in addition to the maximum number of uploads specified in php.ini.
We also usually set a value that is the size limit of the upload that is specified by the business.
For example:
Sina Weibo or QQ space only quasi-Zhang Avatar picture 2M. and upload the atlas can be more than 2M to upload.
So, it's the system that supports larger file uploads.
Judging the size of the file here, we use it to limit the size of the uploaded file we want to specify in the actual business.
Third, to determine whether the suffix name and MIME type is consistent with
There are also bad people in the cyber world. They will insert images into viruses, upload viruses in attachments, and they will insert viruses or yellow images into their web pages.
We need to be able to determine the file suffix and MIME type of the upload.
MIME (Multipurpose Internet Mail Extensions) is a Multipurpose Internet Mail extension type. Is the type of file that sets the extension of an application to be opened by an app, and when the extension file is accessed, the browser automatically opens with the specified application. Many are used to specify some client-customized file names, as well as some ways to open media files.
When judging the suffix and MIME type, we use PHP's function In_array (), which passes two parameters.
The first parameter is the value to be judged;
The second parameter is an array of ranges.
We use this function to determine whether the suffix name and MIME type of the file are within the allowable range.
Iv. Generating file names
Our file upload was successful and will not let it save the original.
Because, some people in the original title of sensitive keywords will violate our laws and regulations.
We can generate random file names using date (), Mt_rand (), or unique ().
V. To determine whether to upload a file
When the file is uploaded successfully, the uploaded temporary file is uploaded to the temporary directory of the system. Produces a temporary file.
A temporary file name is also generated. What we need to do is move the temporary files to the specified directory in the system.
It is not scientific to move or move wrong before moving. Before moving, we need to use the correlation function to determine if the uploaded file is a temporary file.
Is_uploaded_file () passes in a parameter (the cache file name in $_files) to determine if the incoming name is an upload file.
VI. Move temporary files to a specified location
The temp file is a real temporary file and we need to move it to our site directory.
Let us site directory data that other people can access to.
We use: Move_uploaded_file ().
This function is to move the uploaded file to the specified location and name it.
Pass in two parameters:
The first parameter is the specified moving upload file;
The second parameter is a string that specifies the folder and name stitching.
Precautions:
The parameter method in a 1.form form must be post. If a get is not able to upload the file
2.enctype must be Multipart/form-data
Seven, PHP to complete the file upload according to the array and steps
PHP prepares a dedicated system function for file class data $_files, and all relevant data for uploading files is stored in this system function.
In the php file, we print $_files to see the structure of this array:
Array (size=1) 'file'=Array (Size=5) //file name 'name'=string 'psu.jpg'(length=7) //MIME type of file 'type'=string 'Image/jpeg'(length=Ten) //cached files, uploaded images are saved here 'Tmp_name'=string 'E:\wamp\tmp\phpC32A.tmp'(length= at) //error code, see above error code introduction 'Error'=int 0 //file size to upload 'size'=int 225824
Get the structure of the array above.
We can begin the process of processing the file.
The first step is to determine the error code:
<?PHPif($_files['file']['Error'] >0){ Switch($_files['file']['Error']) {//error code is not 0, that is, there was an error during file upload Case '1': Echo'file too large'; Break; Case '2': Echo'file exceeds the specified size'; Break; Case '3': Echo'only some files are uploaded'; Break; Case '4': Echo'file not being uploaded'; Break; Case '6': Echo'the specified folder could not be found'; Break; Case '7': Echo'File Write Failed'; Break; default: Echo"Upload error <br/>"; }}Else{ //The error code is 0, that is, the upload is successful, can be processed later, the processing flow see below}?>
Step two: Determine if the file is out of size
<?PHP//Judgment Errorif($_files['file']['Error'] >0) { //There are errors to stop execution}Else { //the current upload file is correct, run this section of code//determine if the file exceeds the specified size//Unit is byte$MAX _file_size =100000; if($_files['file']['size'] >$MAX _file_size) { //Judging if the uploaded file is larger than the limit we give, back up the upload and generate an error messageExit"file exceeds the specified size"); }}?>
The third step is to determine if the MIME type of the file is correct.
<?PHP/*determine if the suffix and MIME types meet the specified requirements for example: The current project specifies an upload suffix of. jpg or. gif images, then $allowsuffix = array (' jpg ', ' gif ');*///define the allowed suffixes an array group$MYIMG = Explode ('.', $_files['file']['name']);/*explode () cuts a string with the specified character and returns an array, where we use the name '. ' Cut, the result exists in $myimg, the suffix name of the file is the last value of the array*/$myImgSuffix=Array_pop ($MYIMG);/*get the suffix name of the file according to the upload file name use the In_array () function to determine if the upload file is eligible to exit the upload and return an error message when the file suffix is not within our allowed range*/if(!In_array ($myImgSuffix, $allowSuffix)) {Exit ("file suffix name does not match");}/*MIME type and file suffix of the corresponding relationship, we can be queried in many ways, in order to avoid user autonomy to modify the file suffix file can not be used. MIME types must also be restricted to check MIME types in order to prevent the uploader from directly modifying the file suffix to cause the file to be unavailable or to upload files that do not meet the requirements. *///array content is a MIME type that allows uploading$allowMime =Array ("image/jpg", "Image/jpeg", "Image/pjpeg", "Image/gif");if(!in_array ($_files['file']['type'], $allowMime)) {//determine if the MIME type of the uploaded file is within the allowed rangeExit'file format is not correct, please check'); //if it is not within the allowed range, exit the upload and return an error message}?>
Fourth step, generate the specified path and file name
Fifth step, decide whether to upload the file
Is_uploaded_file ()
Sixth step, move the file to the specified location
Using the Move_uploaded_file () function, move the file to the specified location and name it.
<?PHP/*use Move_uploaded_file () to move the uploaded file to the specified location, the first parameter is the upload file, the second parameter is the upload path and name we specified earlier. */if(Move_uploaded_file ($_files['file']['Tmp_name'], $path. $name)) {//prompt for file upload successEcho"Upload Successful"; }Else{/*file move failed, check disk for sufficient space, or if the folder in the Linux class system has sufficient operational permissions*/Echo'Upload failed'; } }Else{echo'Not uploading Files'; }}?>
Eight, file upload progress processing
PHP before 5.4, always need to install additional extensions to monitor the file upload progress. And starting from 5.4, the introduction of the new features of session.upload_progress, we only need to open the configuration in the PHP.ini, the session monitoring file upload progress. In the php.ini.
Note: This chapter requires a session foundation and JavaScript and Ajax basics.
We need to configure, note to view and modify the php.ini file:
Configuration Items |
Description |
Session.upload_progress.enabled |
Whether to enable upload progress report (default on) 1 is on, 0 is off |
Session.upload_progress.cleanup |
Whether to delete the progress data when 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 is not reported. |
session.upload_progress.freq[=1%] |
The rate at which the progress was updated (the number of bytes processed) and the percent '% ' is also supported. |
SESSION.UPLOAD_PROGRESS.MIN_FREQ[=1.0] |
Time interval for update progress (seconds level) |
PHP File Upload