Home php教程 php手册 php上传文件详解

php上传文件详解

Jun 13, 2016 am 10:51 AM
html php upload host Function and deal with document use composition Detailed explanation part page

上传文件功能由两个部分组成,HTML页面和PHP处理部分。HTML页面主要是让用户选择所要上传的文件,php部分让我们可以把文件存储到服务器的指定目录。
一.HTML部分
upload.html
[html] 
 
   

 
         
     
     
        上传Demo: 
       
 
             
             
       
 
     
 
说明:
1.Input标签中type="file",表明把输入作为文件来处理。
2.Enctype规定了在提交这个表单时要使用哪种内容类型。在表单需要二进制数据时,比如文件内容,请使用"multipart/form-data",如果要上传文件,这个属性是必要的。
更多关于enctype的内容参见《HTML
标签的 enctype 属性》

二.php部分
upload.php
[php]
$DST_DIR = '/data/upload/'; 
if ($_FILES['img']['name'] != '') { 
    if ($_FILES['img']['error'] > 0) { 
        echo "上传失败"; 
    } 
    else { 
        if (move_uploaded_file($_FILES['img']['tmp_name'], $DST_DIR.$_FILES['img']['name'])) { 
            echo "上传成功"; 
        } 
        else { 
            echo "上传失败"; 
        } 
    } 

else { 
    echo "请上传文件"; 

说明:
1. 全局变量$_FILE
此数组包含有所有上传的文件信息。
以我们假设文件上传字段的名称如上例所示,为 img。则
$_FILES['img']['name']
客户端上传的文件的原名称。
$_FILES['img']['type']
文件的 MIME 类型,如果浏览器提供此信息的话。一个例子是“image/gif”。不过此 MIME 类型在 PHP 端并不检查,因此不要想当然认为有这个值。$_FILES['img']['size']:已上传文件的大小,单位为字节。
$_FILES['img']['size']
已上传文件的大小,单位为字节。
$_FILES['img']['tmp_name']
文件被上传后在服务端储存的临时文件名。
$_FILES['img']['error']
和该文件上传相关的错误代码。

2. 关于错误码
$_FILES['img']['error']有以下几种类型
UPLOAD_ERR_OK
其值为 0,没有错误发生,文件上传成功。
UPLOAD_ERR_INI_SIZE
其值为 1,上传的文件超过了 php.ini 中 upload_max_filesize选项限制的值。
UPLOAD_ERR_FORM_SIZE
其值为 2,上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。
UPLOAD_ERR_PARTIAL
其值为 3,文件只有部分被上传。
UPLOAD_ERR_NO_FILE
其值为 4,没有文件被上传。
UPLOAD_ERR_NO_TMP_DIR
其值为 6,找不到临时文件夹。PHP 4.3.10 和 PHP 5.0.3 引进。
UPLOAD_ERR_CANT_WRITE
其值为 7,文件写入失败。PHP 5.1.0 引进。

3.move_uploaded_file
文件被上传后,默认地会被储存到服务端的默认临时目录中(除非 php.ini 中的 upload_tmp_dir设置为其它的路径),文件名是随机的。如果该文件没有被移动到其它地方也没有被改名,则该文件将在表单请求结束时被删除。因此需要通过move_uploaded_file移动临时文件。
经实验copy也能完成move_uploaded_file的功能,为啥要用move_uploaded_file呢?有说法是move_uploaded_file会对上传文件做一些检查,防止copy引起的一些安全漏洞。但具体copy会带来什么问题呢?我并没有查到。有知道的同学,欢迎留言。
Anyway,既然php给了特定的函数,必然有一定道理,先这么用吧。

三.安全检查
可以考虑通过$_FILES['img']['size']和$_FILES['img']['type']对上传的文件做一些安全检查,比如限定上传类型,上传文件的大小等。

 

作者;qmhball

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)

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.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

See all articles