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

May 16, 2016 pm 04:52 PM
php Getting Started Tutorial File Upload

一、文件上传

为了让客户端的用户能够上传文件,我们必须在用户界面中提供一个表单用于提交上传文件的请求。由于上传的文件是一种特殊数据,不同于其它的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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

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

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

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

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

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

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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 PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

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.

See all articles