Home >Web Front-end >JS Tutorial >PHP file upload introductory tutorial (explanation with examples)_Basic knowledge

PHP file upload introductory tutorial (explanation with examples)_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 16:52:531881browse

一、文件上传

为了让客户端的用户能够上传文件,我们必须在用户界面中提供一个表单用于提交上传文件的请求。由于上传的文件是一种特殊数据,不同于其它的post数据,所以我们必须给表单设置一个特殊的编码:

复制代码 代码如下:


以上的enctype属性,你可能不太熟悉,因为这常常会被忽略掉。但是,如果http post请求中既有常规数据,又包含文件类数据的话,这个属性就应该显示加上,这样可以提高针对各种浏览器的兼容性。

接下来,我们得向表单中添加一个用于上传文件的字段:

复制代码 代码如下:


上述文件字段在各种浏览器中可能表现会有所不同。对于大多数的浏览器,上述字段都会被渲染成一个文本框加上一个浏览按钮。这样,用户既可以自行输入文件的路径到文本框中,也可以通过浏览按钮从本地硬盘上选择所要上传的文件。但是,在苹果的Safari中,貌似只能使用浏览这种方式。当然,你也可以自定义这个上传框的样式,使它看起来比默认的样式优雅些。

下面,为了更好的阐述怎么样处理文件上传,举一个完整的例子。比如,以下一个表单允许用户向我的本地服务器上上传附件:

复制代码 代码如下:

请上传你的附件:






提示:可以通过php.ini中的upload_max_filesize来设置允许上传文件的最大值。另外,还有一个post_max_size也可以用来设置允许上传的最大表单数据,具体意思就是表单中各种数据之和,所以你也可以通过设置这个字段来控制上传文件的最大值。但是,注意后者的值必须大于前者,因为前者属于后者的一部分表单数据。

PHP file upload introductory tutorial (explanation with examples)_Basic knowledge
 

Figure 1. Upload form displayed in firefox

When this form is submitted, the http request will be sent to upload.php. To show exactly what information is available in upload.php, I print it out in upload.php:

Copy code Code As follows:

header('Content-Type: text/plain');
print_r($_FILES);


Let’s do an experiment below. If I Use the above form to upload a logo of this blog to my local server www.360weboy.me/upload.php and see what information will be output in upload.php:
Copy the code The code is as follows:
Array
                                                                                             [name] => boy .jpg
[type] => image/jpeg
[tmp_name] => D:xampptmpphp1168.tmp
[error] =&g t; 0
                                                                                                                     > )

)



The above is all the information about the currently uploaded file in the global array after the file is uploaded. However, can we guarantee that this information is safe? What if the name or other information has been tampered with? We always need to be vigilant about information from clients!
Parts of the specific http request
In order to better understand file upload, we must check what specific information is included in the http request sent by the client. The attachment I uploaded earlier is the logo of this blog. Because it is a picture, it is not suitable for us to do the above experiment. So, I re-uploaded a test.text text file, which specifically contains the following content:



Copy code

Life Of A Web Boy

Okay. Now when I upload this text file, it will be output in upload.php:



Copy the code (
[attachment] => Array
(
[name] => test.tx t
       [type] => text/plain
                                                                                                                                                                                                                                                                                                     🎜>         )

                                                                                                   
Let’s take a look at the http post request sent by the relevant browser (I have omitted some optional headers):




Copy code

The code is 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 in the above request format that we need to pay attention to, namely name, filename and Content-Type. They respectively represent the field name of the upload file box in the form - attachment, the name of the file uploaded by the user from the local hard disk - test.txt, and the uploaded file format - text/plain (representing a text file). Then, we see a blank line below, which is the specific content of the uploaded file.

2. Security enhancement
In order to enhance the security in file upload, we need to check the tmp_name and size in the $_FILES global array. In order to ensure that the file pointed by tmp_name is indeed the file that the user just uploaded on the client, rather than pointing to something like /etc/passwd, you can use the function is_uploaded_file() in PHP to make a judgment:

Copy code The code is as follows:


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

if (is_uploaded_file($filename)) {
/* Is an uploaded file. */
}

In some cases, after the user uploads the file, it may The content of the successfully uploaded file will be displayed to the user, so checking the above code is particularly important.

Another thing that needs to be checked is the mime-type of the uploaded file, which is the type field of the output array in upload.php mentioned above. What I uploaded in the first example is an image, so the value of $_FILES['attachment']['type'] is 'image/jpeg'. If you plan to only accept mime-type images such as image/png, image/jpeg, image/gif, image/x-png and image/p-jpeg on the server side, you can use code similar to the following to check (just give an example Examples, specific codes, such as error reporting, etc., should follow the mechanism in your system):

Copy code The code is as follows:
                                                                                                                                                                                                            who’ who,’ who’ who’s, image/jpeg',
                                                                                                                                                                                                                                                                                                    allow_mimes)) {
                                                                                                                                                                                                                                                                                      

As you can see, we have ensured that the mime-type of the file meets the server-side requirements. However, it is not enough to prevent malicious users from uploading other harmful files, because this mime-type malicious user can be disguised. For example, the user made a jpg picture, wrote some malicious php code in the metadata of the picture, and then saved it as a file with the suffix php. When this malicious file is uploaded, it will successfully pass the server-side mime-type check and be considered an image, and the dangerous PHP code inside will be executed. The specific image metadata is similar to the following:
Copy the code The code is 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 php code has been added to the Comment field of the image metadata. Therefore, it is obvious that in order to prevent similar dangerous situations from happening, a necessary check must be performed on the extension of the uploaded file. The following code enhances the previous code for checking Mime-type:
Copy the code The code is as follows:


           $allow_mimes = array(
            'image/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 it The file format is not accurate; we only accept image files.');
                                                                                                                                                                     , 0, strrpos($image['name'], '.'));

                                                                                                                                                                                                    🎜>
// Continue processing the uploaded file


Through the above code, we ensure that even if the meta file of the uploaded image contains php code, the image file will be renamed with the suffix File named image format, so the php code in it will not be executed. The above code will not have any negative impact on normal uploaded images.

After performing the above steps 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 achieve this:



Copy code


The code is as follows:

$temp_filename saved in the temporary directory Upload the file, and then successfully save it to the attachment.txt file in the corresponding directory. */
                                                                                                                                                                                                                               The filesize function is used to obtain the size of the uploaded file, and further processing is performed after judgment. This is not detailed here, so you can figure it out yourself.

Okay, let’s stop writing about file upload here for now. I hope this introductory article has been helpful to you.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn