


PHP file upload introductory tutorial (explanation with examples)_Basic knowledge
一、文件上传
为了让客户端的用户能够上传文件,我们必须在用户界面中提供一个表单用于提交上传文件的请求。由于上传的文件是一种特殊数据,不同于其它的post数据,所以我们必须给表单设置一个特殊的编码:
以上的enctype属性,你可能不太熟悉,因为这常常会被忽略掉。但是,如果http post请求中既有常规数据,又包含文件类数据的话,这个属性就应该显示加上,这样可以提高针对各种浏览器的兼容性。
接下来,我们得向表单中添加一个用于上传文件的字段:
上述文件字段在各种浏览器中可能表现会有所不同。对于大多数的浏览器,上述字段都会被渲染成一个文本框加上一个浏览按钮。这样,用户既可以自行输入文件的路径到文本框中,也可以通过浏览按钮从本地硬盘上选择所要上传的文件。但是,在苹果的Safari中,貌似只能使用浏览这种方式。当然,你也可以自定义这个上传框的样式,使它看起来比默认的样式优雅些。
下面,为了更好的阐述怎么样处理文件上传,举一个完整的例子。比如,以下一个表单允许用户向我的本地服务器上上传附件:
请上传你的附件:
提示:可以通过php.ini中的upload_max_filesize来设置允许上传文件的最大值。另外,还有一个post_max_size也可以用来设置允许上传的最大表单数据,具体意思就是表单中各种数据之和,所以你也可以通过设置这个字段来控制上传文件的最大值。但是,注意后者的值必须大于前者,因为前者属于后者的一部分表单数据。
![]() |
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:
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:
[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!
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
Okay. Now when I upload this text file, it will be output in upload.php:
Copy the code
(
[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
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:
$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):
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:
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:
$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:
Okay, let’s stop writing about file upload here for now. I hope this introductory article has been helpful to you.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
