


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.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...

How to obtain the parameters of functions on prototype chains in JavaScript In JavaScript programming, understanding and manipulating function parameters on prototype chains is a common and important task...

Analysis of the reason why the dynamic style displacement failure of using Vue.js in the WeChat applet web-view is using Vue.js...

How to make concurrent GET requests for multiple links and judge in sequence to return results? In Tampermonkey scripts, we often need to use multiple chains...


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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.