Table of Contents
PHP implements file upload and multi-file upload.
Articles you may be interested in:
Home Backend Development PHP Tutorial PHP implements file upload and multiple file upload, _PHP tutorial

PHP implements file upload and multiple file upload, _PHP tutorial

Jul 12, 2016 am 09:02 AM
php File Upload

PHP implements file upload and multi-file upload.

In PHP program development, file upload is a very commonly used function and is also one of the necessary skills for PHP programmers. . Fortunately, implementing the file upload function in PHP is much simpler than in languages ​​such as Java and C#. Below we combine specific code examples to introduce in detail how to implement file upload and multi-file upload functions through PHP.

To use PHP to implement the file upload function, we first write two php files: index.php and upload.php. Among them, the index.php page is used to submit the form request for file upload, and the upload.php page is used to receive the uploaded file and process it accordingly.

First of all, let’s write a simple index.php file. Since it mainly involves html code, it is relatively simple, so we won’t go into details. The detailed code of the index.php page is as follows:

<&#63;php
//设置编码为UTF-8,以避免中文乱码
header('Content-Type:text/html;charset=utf-8');
&#63;>
<!DOCTYPE html>
<html>
<head>
  <title>文件上传表单页面</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
文件1:<input name="upload_file1" type="file" /><br/>
文件2:<input name="upload_file2" type="file" /><br/>
<input type="submit" value="上传" />
</form>
</body>
</html>
Copy after login

It is worth noting that since the HTTP protocol was originally designed, it did not support the file upload function. The default value of the encrypt attribute of the form form is application/x-www-form-urlencoded, which can only be used for general submissions. form request. If the submitted form contains files that need to be uploaded, we need to change the enctype attribute value to multipart/form-data to implement the file upload function. In addition, the method attribute value must be post.

Next, we continue to write the code for the upload.php file.

<&#63;php
//设置编码为UTF-8,以避免中文乱码
header('Content-Type:text/html;charset=utf-8');
$first_file = $_FILES['upload_file1']; //获取文件1的信息
$second_file = $_FILES['upload_file2']; //获取文件2的信息$upload_dir = 'D:/upload/';  //保存上传文件的目录//处理上传的文件1
if ($first_file['error'] == UPLOAD_ERR_OK){
  //上传文件1在服务器上的临时存放路径
  $temp_name = $first_file['tmp_name'];
  //上传文件1在客户端计算机上的真实名称
  $file_name = $first_file['name'];
  //移动临时文件夹中的文件1到存放上传文件的目录,并重命名为真实名称
  move_uploaded_file($temp_name, $upload_dir.$file_name);
  echo '[文件1]上传成功!<br/>';
}else{
  echo '[文件1]上传失败!<br/>';
}

//处理上传的文件2
if ($second_file['error'] == UPLOAD_ERR_OK){
  //上传文件2在服务器上的临时存放路径
  $temp_name = $second_file['tmp_name'];
  //上传文件2在客户端计算机上的真实名称
  $file_name = $second_file['name'];
  //移动临时文件夹中的文件2到存放上传文件的目录,并重命名为真实名称
  move_uploaded_file($temp_name, $upload_dir.$file_name);
  echo '[文件2]上传成功!<br/>';
}else {
  echo '[文件2]上传失败!<br/>';
}
&#63;>
Copy after login

In PHP, when the form request submitted by the browser client contains an uploaded file, PHP will temporarily store the uploaded file in a temporary directory (in Windows operating systems, the default temporary directory is generally C:/Windows/Temp), and then store the relevant information of the uploaded file in the super global variable $_FILES. Therefore, we only need to obtain the uploaded file information through the $_FILES array, and then perform corresponding processing operations on it. Next, let’s take a look at the details of using the print_r() function to output the super global variable $_FILES when uploading two image files A.gif and B.gif through the browser:

Array ( [upload_file1] => Array ( 
 [name] => A.gif (客户端上传时的真实文件名称)
 [type] => image/gif (文件的类型)
 [tmp_name] => C:\Windows\Temp\php9803.tmp (文件上传到PHP服务器后临时存放的路径)
 [error] => 0 (错误信息,0表示没有错误)
 [size] => 87123 (文件大小,单位为字节)
 )
    [upload_file2] => Array (
 [name] => B.gif
 [type] => image/gif
 [tmp_name] => C:\Windows\Temp\php9813.tmp
 [error] => 0
 [size] => 93111
 )
)
Copy after login

In the above example, the parameter names of the two files we uploaded are upload_file1 and upload_file2. Now, we let multiple files in the form use the same parameter name upload_file, and resubmit the two files just uploaded in the form of parameter arrays for upload. At this time, we need to modify the two file file fields in the index.php page to the following html code:

  • File 1:
  • File 2:

In addition, we also need to make corresponding modifications to the upload.php page:

<&#63;php
//设置编码为UTF-8,以避免中文乱码
header('Content-Type:text/html;charset=utf-8');
$fileArray = $_FILES['upload_file'];//获取多个文件的信息,注意:这里的键名不包含[]

$upload_dir = 'D:/upload/'; //保存上传文件的目录
foreach ( $fileArray['error'] as $key => $error) {
  if ( $error == UPLOAD_ERR_OK ) { //PHP常量UPLOAD_ERR_OK=0,表示上传没有出错
    $temp_name = $fileArray['tmp_name'][$key];
    $file_name = $fileArray['name'][$key];
    move_uploaded_file($temp_name, $upload_dir.$file_name);
    echo '上传[文件'.$key.']成功!<br/>';
  }else {
    echo '上传[文件'.$key.']失败!<br/>';
  }
}
&#63;>

Copy after login

Similarly, we use the print_r() function to view the details of the superglobal variable $_FILES in the above example:

Array ( 
 [upload_file] => Array ( 
 [name] => Array ( 
  [0] => A.gif
  [1] => B.gif  
  ) 
 [type] => Array ( 
  [0] => image/gif
  [1] => image/gif  
  ) 
 [tmp_name] => Array (
  [0] => C:\Windows\Temp\php87B9.tmp
  [1] => C:\Windows\Temp\php87BA.tmp
  ) 
 [error] => Array ( 
  [0] => 0
  [1] => 0  
  ) 
 [size] => Array ( 
  [0] => 87123
  [1] => 93111  
  )
 )
)
Copy after login

Note 1: Under the default configuration of PHP, an error will occur if the uploaded file size exceeds a certain range. Please refer to the solution to the problem of how to modify the size limit of PHP uploaded files mentioned at the end of the article.
Note 2: The above PHP code for processing file uploads is just a simple introductory example and cannot be used directly as formal code because there are many security factors that require additional attention that have not been considered, such as: file type, file size, and uploaded files. Duplicate names, etc.
Note 3: If the uploaded file name contains Chinese characters, it may cause the file name to be garbled. At this time, you need to use the function iconv() to convert the encoding of the file name.

Previously we learned how to use PHP to implement file upload and multiple file upload. However, under the default configuration of PHP, when the uploaded file size exceeds a certain limit, we will get the following error message:

Warning: POST Content-Length of 625523488 bytes exceeds the limit of 8388608 bytes in Unknown on line 0
上述错误信息的大致意思是,我们使用POST请求提交的数据大小超过了服务器的最大限制数(8388608字节=8MB)。

出现上述错误的原因是,在PHP的配置文件php.ini中,默认存在如下配置信息(在php.ini中,行首的分号";"表示当前行是注释,不会生效):

;脚本解析输入数据(类似 POST 和 GET)允许的最大时间,单位是秒。 它从接收所有数据到开始执行脚本进行测量的。 
max_input_time = 60

;允许客户端单个POST请求发送的最大数据
post_max_size = 8M

;是否开启文件上传功能
file_uploads = On

;文件上传的临时存放目录(如果不指定,使用系统默认的临时目录)
;upload_tmp_dir =

;允许单个请求上传的最大文件大小
upload_max_filesize = 2M

;允许单个POST请求同时上传的最大文件数量
max_file_uploads = 20

Copy after login

From the above configuration information, we can see that PHP's default configuration information is the "culprit" that causes the file size to exceed the limit when uploading PHP files. The author has provided the Chinese annotation information corresponding to each command option in the above configuration information. You can modify the php.ini configuration file accordingly according to your actual needs.

The above is the entire content of this article to help you implement the php file upload function.

Articles you may be interested in:

  • PHP upload file size limit
  • php file upload suffix name and file type comparison table (covering almost all files)
  • PHP image file upload implementation code
  • How to handle multiple file uploads in ordinary forms in php
  • php file upload class code
  • php.ini changes the size of php upload files Detailed explanation of restriction methods
  • php jquery multi-file upload simple example
  • php multi-file upload implementation code
  • php multi-file upload and download example sharing

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1084544.htmlTechArticlePHP implements file upload and multi-file upload. In PHP program development, file upload is a very commonly used function. , is also one of the essential skills for PHP programmers. Happily, in...
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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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

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 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

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

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 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