PHP File Upload

Source: Internet
Author: User
Tags html form php file upload

File uploads can be implemented via the HTTP protocol. To use the file upload function, the first thing to do in the configuration file php.ini upload settings, and then through the predefined constants $_files upload files to make some restrictions and judgments, and finally through the Move_uploaded_file () function to implement the upload.
Configuring the php.ini fileTo implement the upload function, first to open the file upload in the php.ini, and some of the parameters to make reasonable settings to findFile uploadsitem, you can see the following 3 property values, meaning the meanings are as follows. 1, File_uploads: If the value is on, the server supports file upload, if off, it is not supported. 2, Upload_tmp_dir: Upload file temp directory. Before the file is successfully uploaded, the file is first stored in a temporary directory on the server side. If you want to specify a location, set it here. Otherwise, you can use the system default directory. 3.upload_max_filesize: The maximum value, in megabytes, that the server allows for uploading files. The system defaults to 2MB, and the user can set it up by itself. In addition to the file uploads key, several properties also affect the ability to upload files. 4, the maximum time that an instruction in max_execution_time:php can execute, the unit is the second. 5, the memory space allocated by an instruction in memory_limit:php, the unit is MB. After the php.ini file configuration is complete, you need to restart Apache for the configuration to take effect

pre-defined variable $_filesThe $_files variable stores information about the uploaded file, which is useful for uploading functions. The variable is a two-dimensional array.
The following table lists the saved information
Element name Description
$_files[filename][name] The file name of the uploaded file is stored, such as Test.txt,tu.jpg
$_files[filename][size] Stores the file size in bytes

$_files[filename][tmp_name ]

When uploading a file, it is first saved as a temporary file in the temp directory. The variable is a temporary file name.
$_files[filenam][type] The type of upload file.
$_files[filename][error] The result of uploading the file is stored. If 0 is returned, the file upload succeeds.

UPLOAD_ERR_OK value: 0; No error occurred, file upload succeeded

Upload_err_ini_size value: 1; The uploaded file exceeds the value of the Upload_max_filesize option limit in php.ini

Upload_err_form_size value: 2; the size of the uploaded file exceeds the value specified by the Max_file_size option in the HTML form

Upload_err_partial value: 3; Files are only partially uploaded

Upload_err_no_file value: 4; No file is uploaded, value: 5; Upload file size of 0


Attention:

When uploading a file with a form, be sure to add the attribute content enctype= "Multipart/form-data", otherwise you will be reported an exception when obtaining the file information with $_files[filename].

For example: To implement an upload file domain, through the $_files variable output upload file data, the code is as follows:

<form action= "" method= "Post" enctype= "Multipart/form-data" ><!--upload file domain, type file--><input type= " File "  name=" upfile ><!--submit button--><input type= "Submit" name= "submit" value= "Upload" ></form>< The!--processing form returns the result--><?php    if (!empty ($_files)) {foreach ($_files[' upfile ') as $name + = $value) {echo $name. ' = '. $value. ' <br> ';        }    }? >

The result of the operation is:


File Upload functionPHP uses the Move_uploaded_file () function to implement file uploads.The move_uploaded_file () function uploads the specified file to the location specified in the server. Returns true if successful, otherwise false. The syntax is as follows:
BOOL Move_uploaded_file (string filename,string destination) parameter filename Specifies the temporary filename of the uploaded file, which is $_files[tmp_name] The parameter destination specifies the new path and name saved after the file is uploaded. For example: If you need to create a Upfile folder to create an upload form, allow uploading 2MB of the following, format JPG image file, the upload text is saved in the root directory under the Upfile folder, upload successfully browse the directory, the code is as follows:
<meta charset= "UTF-8" ><!--upload form must have enctype properties--><form action= "method=" post "enctype=" multipart/ Form-data "> <!--Upload a file field, type file--> <input type=" file "name=" Up_file "> <!--Submit button--< Input type= "Submit" name= "submit" value= "upload" ></form><!--process form return results--><?php if (!empty File][name]) {//To determine if there is an upload file $fileinfo =$_files[up_file];//Assign the file information to the variable $fileinfo $type =strstr ($fileinfo [' name '], '. '        ); if ($type! = ". jpg") {echo] The file you uploaded is not in the correct format!        "; }else{if ($fileinfo [' Size ']<2097152&& $fileinfo [' size ']>0) {//determine file size $path = "upfile/"                . $_files["Up_file" ["Name"];//define the path of the uploaded file Move_uploaded_file ($fileinfo [' Tmp_name '], $path);//Upload file Browse the directory if the upload succeeds if (Is_dir ("upfile/")) {//Determine if the file name is a directory $dir =scandir ("upfile/");//Use Scandir () The function obtains all file and directory foreach ($dir as $value) {echo $value. ' <bR> '; }}else{Echo ' directory path Error!                ';            }}else{echo "File size does not meet the requirements"; }}}?>

The operation results are as follows:

Note: This method when uploading pictures, on the computer to see the file name will be garbled in Chinese (because the computer Chinese is gb2312 encoded) I provide two solutions: 1: Conversion code, change the name to gb2312, and then rename the file name, read the time to convert to UTF-8
if (!empty ($_files[up_file][name])) {//Determine if there is an upload file    $fileinfo =$_files[up_file];//Assign the file information to the variable $fileinfo    $type = Strstr ($fileinfo [' name '], '. ');    if ($type! = ". jpg") {        echo] The file you uploaded is not in the correct format! ";    } else{        if ($fileinfo [' Size ']<2097152&& $fileinfo [' size ']>0) {//Determine the file size            $file _name=iconv (" UTF-8 "," gb2312 ", $_files[" Up_file "[" name "]);//Convert UTF-8 encoding to gb2312            $path =" upfile/". $file _name;//define the path to the uploaded file            move_uploaded_file ($fileinfo [' Tmp_name '], $path);//upload file            //upload successful after browsing the directory            if (Is_dir ("upfile/")) {// Determine if the file name is a directory                $dir =scandir ("upfile/"),//Use the Scandir () function to get all files and directories                foreach ($dir as $value) {                    echo iconv (" gb2312 "," UTF-8 ", $value). ' <br> ';//convert gb2312 encoding to UTF-8                }            }else{                echo ' Directory path Error! ';            }        } else{            echo "File size does not meet the requirements";}}    }

2: Rename the file name as a combination of English + numeric (can use time to name)









PHP File Upload

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.