PHP Upload principle and operation implementation, and php Upload Principle

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

PHP Upload principle and operation implementation, and php Upload Principle

There are many well-encapsulated function libraries for PHP File Upload. You can use them directly.

This article only talks about the upload principle and simple upload operations, and the old bird ignores the ha _ ^ ~

There are also some security judgments, such as: the server restricts the ability to receive image files, while the client maliciously changes the extension of the virus file to an image matching file for upload.

 

(For example, if a single file is uploaded, the principle of multiple files remains the same, but there are more tips)

 

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

1. Form label enctype attributes

In the form, enctype = "multipart/form-data" is used to set the MIME encoding of the form.
By default, the encoding format is application/x-www-form-urlencoded and cannot be used for file upload;
Only when multipart/form-data is used and the submission method is Post can the complete file data be transmitted.

 

2,MAX_FILE_SIZEHide Fields

MAX_FILE_SIZE the hidden field (in bytes) must be placed before the input field of the file, and its value is the maximum size of the received file. This is a suggestion for the browser. PHP will also check this item.
This setting can be simply bypassed on the browser side, so do not expect this feature to block large files. (But in view of the friendliness, it is best to add this item to the form, because it can avoid the trouble of uploading a large file after you wait for the upload of a large file .)

 

Upload. php

<?php        print_r($_FILES);?>

We can see that:

Array ([file] => Array ([name] => photo file .jpg [type] => image/jpeg [tmp_name] => F: \ wamp \ tmp \ php41BB. tmp [error] => 0 [size] => 73886 ))

 

3. Application of global variable $ _ FILES

$ _ FILES ['file'] ['name'] indicates the original file name to be uploaded.

$ _ FILES ['file'] ['type'] indicates the MIME type of the uploaded file.

$ _ FILES ['file'] ['SIZE'] size of the uploaded file, in bytes

$ _ FILES ['file'] ['tmp _ name'] temporary file name stored on the server after the file is uploaded ()

$ _ FILES ['file'] ['error'] error code for file Upload

 

4. By default, the uploaded file is saved in the temporary folder on the server, and its directory is set in php. ini.

Some common settings related to file upload in php. ini:

File_uploads; Specifies whether to enable file upload over HTTP. ON is enabled by default.

Upload_tmp_dir; upload the file to the place where the temporary file is stored on the server. If it is not specified, the default Temporary Folder will be used.

Upload_max_filesize; that is, the maximum file size that can be uploaded. The default value is 2 MB.

Post_max_size refers to the maximum value that can be received by the form POST to PHP, including all values in the form. The default value is 8 Mb.

 

The following is the complete code for uploading a single file, because it is just as you want to write, it may be a bit messy with logical nesting, understanding the principle is the most important.

<? Php // get the information of the uploaded file $ fileName = $ _ FILES ['file'] ['name']; $ fileType = $ _ FILES ['file'] ['type']; $ fileError = $ _ FILES ['file'] ['error']; $ fileSize = $ _ FILES ['file'] ['SIZE']; $ tempName = $ _ FILES ['file'] ['tmp _ name']; // temporary file name // define the upload file type $ typeList = array ("image/jpeg", "image/jpg", "image/png", "image/gif "); // define the allowed type if ($ fileError> 0) {// determine the Upload File error number switch ($ fileError) {case 1: $ message = "the uploaded file exceeds php. upload_max_filesize in ini Option value. "; Break; case 2: $ message =" the size of the uploaded file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form. "; Break; case 3: $ message =" only part of the file is uploaded. "; Break; case 4: $ message =" no file is uploaded. "; Break; case 6: $ message =" the Temporary Folder cannot be found. "; Break; case 7: $ message =" file write failed "; break; case 8: $ message =" File Upload interrupted due to PHP extension "; break ;} exit ("File Upload Failed :". $ message) ;}if (! Is_uploaded_file ($ tempName) {// determine whether the file is POST-uploaded ("not uploaded through http post");} else {if (! In_array ($ fileType, $ typeList) {exit ("the uploaded file is not of the specified type");} else {if (! Getimagesize ($ tempName) {// prevents users from uploading malicious files. For example, change the virus file extension to the image format exit ("the uploaded file is not an image ");}} if ($ fileSize> 100000) {// specifies the size of the file to be uploaded in a specific form. exit ("the size of the uploaded file exceeds the limit ");} else {// avoid garbled Chinese names for uploaded files $ fileName = iconv ("UTF-8", "GBK", $ fileName ); // convert the character encoding captured by iconv from UTF-8 to gbk and output $ fileName = str_replace (". ", time (). ". ", $ fileName); // Add a timestamp after the image name to avoid overwriting if (move_uploaded_file ($ tempName," uploads /". $ fileName) {echo "File Uploaded successfully! ";}Else {echo" File Upload Failed ";}}}?>

 

5. Some common functions for php File Uploading: (I will not post them for specific usage. Check the API documentation)

File_exists check whether the file or directory exists

Is_uploaded_file: checks whether the file is uploaded through http post.

Move_uploaded_file: Move the uploaded file to a new location.

Is_writable: determines whether a given file name can be written.

Iconv character encoding

Str_replace string replacement (change the file name to prevent duplicate names)

Getimagesize check whether it is an image file (other types of files can be detected even if the suffix is changed)


How php implements log management (recording user operations)

The two functions are implemented respectively to implement logon logs and operation logs, and to customize the number of two functions. DO these two functions respectively when the user logs on and adds, modifies, and deletes them. Information is recorded in the database table.

How can I achieve progress bar during php file upload?

Jquery has many plug-ins to implement the style of File Upload progress.

Ps: since you have such a personality, I will tell you the principle of implementation. Let's get the details by yourself.

Normal page access is synchronized, that is, request --> feedback, and the progress bar requires real-time data. Therefore, normal pages cannot implement this function, it is necessary to obtain the progress data through the asynchronous ajax cycle. The source of the data is of course sent by the server, so a serious problem occurs. php cannot obtain the status during file transfer. fortunately, the founder of php wrote an APC extension (another extension is uploadprogress). Using the extension syntax and ajax, the dom object on the page is operated by js, And a progress bar is achieved.
You understand the principles, and it's hard for you to do it.

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.