Home Backend Development PHP Tutorial PHP实现文件上传和多文件上传_PHP

PHP实现文件上传和多文件上传_PHP

May 29, 2016 am 11:47 AM
php file upload

在PHP程序开发中,文件上传是一个使用非常普遍的功能,也是PHP程序员的必备技能之一。值得高兴的是,在PHP中实现文件上传功能要比在Java、C#等语言中简单得多。下面我们结合具体的代码实例来详细介绍如何通过PHP实现文件上传和多文件上传功能。

要使用PHP实现文件上传功能,我们先来编写两个php文件:index.php和upload.php。其中,index.php页面用于提交文件上传的表单请求,upload.php页面用于接收上传的文件并进行相应处理。

首先,我们来编写一个简单的index.php文件,由于其中涉及的主要是html代码,比较简单,因此不再赘述,index.php页面的详细代码如下:

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

值得注意的是,由于在HTTP协议设计之初,它并不支持文件上传功能,form表单的encrypt属性的默认值为application/x-www-form-urlencoded,它只能用于提交一般的表单请求。如果提交的表单中包含需要上传的文件,我们需要将enctype的属性值改为multipart/form-data才能实现文件上传功能。此外,method的属性值必须为post。

接着,我们继续编写upload.php文件的代码。

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

在PHP中,当浏览器客户端提交过来的表单请求中包含上传的文件时,PHP会将上传的文件先暂时存放在临时目录中(在Windows操作系统中,默认的临时目录一般为C:/Windows/Temp),然后将上传文件的相关信息存放在超全局变量$_FILES中。因此,我们只需要通过$_FILES数组获取上传的文件信息,然后对其进行相应的处理操作即可。下面,我们来看看通过浏览器上传A.gif和B.gif两个图片文件时,使用print_r()函数输出超全局变量$_FILES的详细信息:

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

在上面的例子中,我们上传的两个文件参数名分别为upload_file1和upload_file2。现在,我们让表单中的多个文件以相同的参数名upload_file,将刚才上传的两个文件以参数数组形式再次提交上传。此时,我们需要将index.php页面中的两个file文件域修改为如下html代码:

  • 文件1:
  • 文件2:

此外,我们还需要对upload.php页面进行相应的修改:

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

同样的,我们使用print_r()函数来查看上面例子中的超全局变量$_FILES的详细信息:

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

备注1:在PHP的默认配置下,上传的文件大小超出一定的范围将会出错,请参文末提到的如何修改PHP上传文件的大小限制问题的解决方法。
备注2:上述处理文件上传的PHP代码只是一个简单的入门示例,并不能直接作为正式代码使用,因为还有许多需要额外注意的安全因素没有考虑,例如:文件的类型、文件的大小以及上传文件的名称重复等。
备注3:如果上传的文件名称中包含中文,可能引起文件名称乱码问题。此时,需要使用函数iconv()来转换文件名称的编码。

前面我们了解了如何使用PHP实现文件上传和多文件上传。不过,在PHP的默认配置情况下,当上传的文件大小超出一定的限制时,我们将得到如下的错误提示信息:

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

从上面的配置信息中我们可以看出,PHP的默认配置信息就是导致PHP文件上传时提示文件大小超出限制的「罪魁祸首」。笔者已经在上述配置信息中给出了各个指令选项对应的中文注释信息,大家可以根据自己的实际需求情况对php.ini配置文件进行相应的修改。

以上就是本文的全部内容,帮助大家实现php文件上传功能。

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 file upload tutorial: How to upload files using HTML forms PHP file upload tutorial: How to upload files using HTML forms Jun 11, 2023 am 08:10 AM

PHP file upload tutorial: How to use HTML forms to upload files In the process of website development, the file upload function is a very common requirement. As a popular server scripting language, PHP can implement the file upload function very well. This article will introduce in detail how to use HTML forms to complete file uploads. 1. HTML form First, we need to use an HTML form to create a file upload page. In the HTML form, the enctype attribute needs to be set to "multipart/form-

How to handle file upload in PHP? How to handle file upload in PHP? May 11, 2023 pm 10:31 PM

With the continuous development of Internet technology, the file upload function has become an essential part of many websites. In the PHP language, we can handle file uploads through some class libraries and functions. This article will focus on the file upload processing method in PHP. 1. Form settings In the HTML form, we need to set the enctype attribute to "multipart/form-data" to support file upload. The code is as follows: &lt;formaction="upload.

PHP file upload security guide: How to use the $_FILES array to obtain uploaded file information PHP file upload security guide: How to use the $_FILES array to obtain uploaded file information Jul 30, 2023 pm 06:53 PM

PHP file upload security guide: How to use the $_FILES array to obtain uploaded file information Summary: File upload is one of the common functions in web development. However, incorrect file upload implementation can lead to security vulnerabilities, bringing potential risks to the application. This article will introduce how to use PHP's $_FILES array to safely obtain uploaded file information, and combine it with some code examples to help readers better understand. To set appropriate file upload limits in PHP, we can use the php.ini file to

Tips for handling PHP file upload encoding errors and generating corresponding error prompts Tips for handling PHP file upload encoding errors and generating corresponding error prompts Aug 06, 2023 am 09:51 AM

Tips for handling PHP file upload encoding errors and generating corresponding error prompts. File upload is a very common requirement when developing web applications. When processing PHP file uploads, we often encounter encoding errors. This article will introduce some techniques for handling PHP file upload encoding errors and generating corresponding error prompts. In PHP, file uploads are accessed through the $_FILES global variable. You can obtain the name, size, temporary file path and other information of the uploaded file through $_FILES

How to write a simple file upload and download function via PHP How to write a simple file upload and download function via PHP Sep 24, 2023 am 08:12 AM

How to write a simple file upload and download function through PHP. With the development of Internet technology, file upload and download functions have become one of the necessary functions for many websites. By writing a simple file upload and download function, users can easily upload and download files and improve user experience. This article will introduce how to use PHP to write a simple file upload and download function, and provide specific code examples. 1. Implementation of the file upload function. Create a form. First, create a form on the HTML page for users to upload files.

PHP file upload methods and summary of frequently asked questions PHP file upload methods and summary of frequently asked questions Jun 08, 2023 pm 09:27 PM

Summary of PHP file upload methods and frequently asked questions File upload is one of the common functions in web development and can be used for users to upload avatars, files, etc. PHP provides a convenient file upload processing method. This article will introduce the PHP file upload method and a summary of common problems in detail. 1. PHP file upload method HTML form To implement file upload, you need to use an HTML form, in which the enctype attribute needs to be set to "multipart/form-data", so that the browser

How to use PHP to develop file upload and download modules in CMS How to use PHP to develop file upload and download modules in CMS Jun 21, 2023 pm 12:13 PM

With the continuous development of the Internet, more and more websites require file upload and download functions. As an open source server-side scripting language, PHP has a wide range of application scenarios and industry recognition. CMS (Content Management System) is one of our common website types. This article will discuss how to use PHP to develop the file upload and download modules in CMS. 1. File upload module 1. Basic principle of uploading files The basic principle of file upload is to transfer files from the client

How to use PHP to implement a simple online file upload and download system How to use PHP to implement a simple online file upload and download system Sep 24, 2023 pm 03:13 PM

How to use PHP to implement a simple online file upload and download system requires specific code examples. In the Internet age, file transfer and sharing are very common needs. Whether you are an individual or a business, you need to handle uploading and downloading files conveniently and quickly. As a powerful server-side scripting language, PHP provides a wealth of functions and tools to easily implement file upload and download functions. This article will introduce how to use PHP to implement a simple online file upload and download system, and provide detailed code examples.

See all articles