PHP file on the introduction of the door Tutorial (example) _ Basic knowledge

Source: Internet
Author: User
Tags http post php code

First, File upload

In order for client users to upload files, we must provide a form in the user interface to submit a request for an uploaded file. Since the uploaded file is a special type of data that differs from other post data, we must set a special encoding for the form:

Copy Code code as follows:
<form action= "upload.php" method= "POST" enctype= "Multipart/form-data" ></form>


The enctype attribute above, you may not be familiar with it, as this is often overlooked. However, if the HTTP POST request has both regular data and file class data, this property should be displayed plus, which can improve compatibility for various browsers.

Next, we need to add a field to the form for uploading files:

Copy Code code as follows:
<input type= "file" name= "attachment" >


The above file fields may behave differently in various browsers. For most browsers, the above fields are rendered as a text box plus a navigation button. This allows the user to either enter the path of the file to the text box, or select the file to upload from the local hard drive by using the browse button. However, in the Apple Safari, it seems that the only way to use browsing. Of course, you can also customize the style of the upload box to make it look more elegant than the default style.

Below, for a better description of how to deal with file uploads, give a complete example. For example, one of the following forms allows users to upload attachments to my local server:

Copy Code code as follows:
<p> please upload your attachment:</p>
<form action= "upload.php" method= "POST" enctype= "Multipart/form-data" >
<input type= "file" name= "attachment" >
<input type= "Submit" value= "Upload Attachment" >
</form>

Tip: You can set the maximum number of files allowed to upload by upload_max_filesize in php.ini. In addition, there is a post_max_size can also be used to set the maximum allowed to upload the form data, which means the sum of the various data in the form, so you can also set this field to control the maximum size of uploaded files. However, note that the latter value must be greater than the former, because the former is part of the latter's form data.

Figure 1. Upload form displayed in Firefox

When this form is submitted, the HTTP request is sent to the upload.php. In order to show what specific information can be used in upload.php, I print it out in upload.php:

Copy Code code as follows:

Header (' Content-type:text/plain ');
Print_r ($_files);


Here is a test, if I upload a blog logo to my local server www.360weboy.me/upload.php through the above form, and see what information will be output in upload.php:
Copy Code code as follows:
Array
(
[Attachment] => Array
(
[Name] => boy.jpg
[Type] => image/jpeg
[Tmp_name] => D:\xampp\tmp\php1168.tmp
[ERROR] => 0
[Size] => 11490
)

)


The above is all the information about the current uploaded file in the global array after the file is uploaded. But can we guarantee that the information is secure if name or other information has been tampered with? We always need to be alert to information from the client!

Various parts of a specific HTTP request
To better understand file uploads, we have to check that the HTTP requests sent by the client contain the specific information. Previously I uploaded the attachment is the logo of this blog, because it is a picture, not very suitable for us to do the above experiments. So, I'm uploading a test.text text file that contains the following details:

Copy Code code as follows:

360w
360days
Life of A Web Boy

Okay. Now I upload this text file and output it in upload.php:
Copy Code code as follows:


Array
(
[Attachment] => Array
(
[Name] => test.txt
[Type] => Text/plain
[Tmp_name] => D:\xampp\tmp\php51C0.tmp
[ERROR] => 0
[Size] => 40
)

)

Let's take a look at the HTTP POST requests sent by the relevant browser (some of the optional headers I omitted):
Copy Code code as follows:


post/upload.php http/1.1
Host:www.360weboy.me
referer:http://www.360weboy.me/
Multipart/form-data; boundary=---------------------------24464570528145
content-length:234

-----------------------------24464570528145
Content-disposition:form-data; Name= "Attachment"; Filename= "Test.txt"
Content-type:text/plain

360weboy

360days

Life of A Web Boy
-----------------------------24464570528145--

There are several fields from the above request format we should focus on the name, filename, and content-type. They represent the name of the field in the form-attachment the upload file box, the filename that the user uploaded from the local hard drive- Test.txt, as well as uploaded file format –text/plain (representing text files). Then, we see a line below the empty line, which is the specific contents of this upload file.

Ii. Strengthening of security
To enhance security in file uploads, we need to check the tmp_name and size in the $_files global array. To make sure that the file that Tmp_name points to is really just a file that the user uploaded on the client, rather than pointing to a similar/etc/passwd, you can use the function is_uploaded_file () in PHP to make a judgment:

Copy Code code as follows:


$filename = $_files[' attachment '] [' tmp_name '];

if (Is_uploaded_file ($filename)) {
/* is an uploaded file. */
}

In some cases, when the user uploads the file, it may display the contents of the uploaded files to the user to see, then the above code is particularly important to check.

Another thing to check is the mime-type of the uploaded file, which is the Type field of the output array in the upload.php above. I uploaded a picture in the first example, so the value of $_files[' attachment ' [' type '] is ' image/jpeg '. If you intend to accept only image/png, Image/jpeg, Image/gif, Image/x-png, and image/p-jpeg images on the server side, you can check them with code similar to the following (just for example, the specific code , such as error, should follow the mechanism in your system):

Copy Code code as follows:

$allow _mimes = Array (
' Image/png ',
' Image/x-png ',
' Image/gif ',
' Image/jpeg ',
' Image/pjpeg '
);

$image = $_files[' attachment '];

if (!in_array ($image [' type '], $allow _mimes)) {
Die (' Sorry, you uploaded the file format is not accurate; we only accept picture files. ')
}

Continue processing uploaded image files

As you can see, we've made a note of the mime-type of the file to meet the server-side requirements. However, this is not enough to prevent a malicious user from uploading other unwanted files, because this mime-type malicious user can be disguised. For example, the user made a JPG image, wrote some malicious PHP code in the image metadata, and then saved it as a file with a suffix named PHP. When this malicious file is uploaded, it will go through the server side for Mime-type inspection, is considered a picture, the inside of the dangerous PHP code will be executed. The metadata for the specific picture is similar to the following:
Copy Code code as follows:


File name:image.jpg
File size:182007 bytes
File date:2012:11:27 7:45:10
resolution:1197 x 478
Comment:passthru ($_post[' cmd ']); __halt_compiler ();

We can see that the PHP code is added to the comment field of the picture metadata. Therefore, it is clear that in order to prevent such a dangerous situation, you must also make a necessary check on the extension of the uploaded file. The following code reinforces the previous check Mime-type code:
Copy Code code as follows:


$allow _mimes = Array (
' Image/png ' => '. png ',
' Image/x-png ' => '. png ',
' Image/gif ' => '. gif ',
' Image/jpeg ' => '. jpg ',
' Image/pjpeg ' => '. jpg '
);

$image = $_files[' attachment '];

if (!array_key_exists ($image [' type '], $allow _mimes)) {
Die (' Sorry, you uploaded the file format is not accurate; we only accept picture files. ')
}

Gets the filename of the omitted suffix name:
$filename = substr ($image [' name '], 0, Strrpos ($image [' name '], '. '));

Add suffix Name
$filename. = $allow _mimes[$image [' type ']];

Continue processing the uploaded files

Through the above code, we ensure that even if the upload of the image of the metafile contains the PHP code, the image file will be the same name as the suffix of the picture format file, so the PHP code will not be executed. The above code does not have any negative effect on the normal uploaded picture.

With the steps above to improve security, if you just want to save the uploaded file to a specified directory, you can use PHP's default function, Move_uploaded_file, to implement the following:

Copy Code code as follows:


$tmp _filename = $_files[' attachment '] [' tmp_name '];
$filename = '/path/to/attachment.txt ';

if (Move_uploaded_file (Tmp_filename, $filename)) {
/* $temp _filename Save the upload file in the temp directory, and then successfully save it to the Attachment.txt file in the corresponding directory. */
}

You may also be the size of the upload file limit, then you can use the FileSize function to get the size of the upload file, the judge to do further processing, this specific is not in this will be, their own to toss it.

Well, for the file upload for the time being to write here. I hope this introductory article will be of some help to you.

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.