Home Backend Development PHP Tutorial Detailed explanation of PHP file upload operation examples

Detailed explanation of PHP file upload operation examples

Jan 14, 2017 pm 02:17 PM
php file upload

The example of this article analyzes the PHP file upload operation. Share it with everyone for your reference, the details are as follows:

File upload

occurs in the request sent by the browser to the server.

File, for the browser, is just a special type of data in the form.

Data in the browser form, two types:

String type (byte stream encoding)

File type (binary encoding), the file is in the form data Part of

Server perspective:

Process the data in the form when accepting the browser request. Different processing methods are used according to different data types:

String type, stored in the $_POST variable (memory)

File type data, stored in the upload temporary directory

When the form is submitted, the browser will behave as follows:

The content in the form is of string type. Even if a file field is added, attributes need to be added to the form to inform the browser that more than just strings are uploaded. type data. enctype="multipart/form-data"

<body>
  <form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    </br>
    <input type="submit" value="submit">
  </form>
</body>
Copy after login

After the php server receives the form data of the file type, it stores the file in a temporary directory (it is a temporary file and is valid within the script cycle)

; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
; http://php.net/upload-tmp-dir
;upload_tmp_dir =
Copy after login

Persistently store temporary files

move_uploaded_file(src_url,goa_url)
Copy after login

$_FILES, which stores uploaded file information including temporary addresses

 PHP文件上传操作实例详解

Error type:

0-1-2-3-4-6-7

0 means there is no error

1 means the file is larger than the php setting

; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 2M
Copy after login

2 means the file is larger than the form setting max_file_size

<input type=&#39;hidden&#39; name=&#39;MAX_FILE_SIZE&#39; value=&#39;1024&#39;>
Copy after login

3 means that the file upload is incomplete

4 means that no file is uploaded

5 means that a 0-byte file (empty file) is logically uploaded

6 means the temporary upload directory was not found (insufficient permissions)

7 means file writing failed (disk space, permissions)

Maximum number of uploaded files allowed by php

; Maximum number of files that can be uploaded via a single request
max_file_uploads = 20
Copy after login

There is a maximum value limit for post

Once exceeded, PHP cannot process post and file values ​​normally and may be empty values

; Maximum size of POST data that PHP will accept.
; http://php.net/post-max-size
post_max_size = 8M
Copy after login

In type detection

The suffix name and mime are both browse Provided by the server, PHP extension fileinfo is required to complete the check of file information (function process and object-oriented)

;extension=php_fileinfo.dll

$finfo = new Finfo(FILEINFO_MIME_TYPE);
$mine_type = $finfo->file($file[&#39;tmp_name&#39;]);
Copy after login

Molecular directory storage uploaded files

Principle: business logic, number of files, time

Create directory mkdir()

Check directory is_dir()

<?php
upload($_FILES[&#39;file&#39;]);
function upload($file){
  if($file[&#39;error&#39;]!=0){
    return false;
  }
  //3M
  $max_size = 3145728;
  if($max_size<$file[&#39;size&#39;]){
    return false;
  }
  //设置一个后缀名与mime的映射关系
  $type_map = array(
    &#39;.jpeg&#39;=>array(&#39;image/jpeg&#39;,&#39;image/pjpeg&#39;),
    &#39;.jpg&#39;=>array(&#39;image/jpeg&#39;,&#39;image/pjpeg&#39;),
    &#39;.png&#39;=>array(&#39;image/png&#39;,&#39;image/x-png&#39;),
    &#39;.gif&#39;=>array(&#39;image/gif&#39;)
  );
  //后缀
  $allow_ext_list = array(&#39;.jpeg&#39;,&#39;.png&#39;,&#39;.jpg&#39;);
  $ext = strtolower(strrchr($file[&#39;name&#39;],&#39;.&#39;));
  if(!in_array($ext,$allow_ext_list)){
    echo &#39;不支持该图片格式&#39;;
    return false;
  }
  //MIME
  $allow_mime_list = array();
  foreach($allow_ext_list as $val){
    $allow_mime_list = array_merge($allow_mime_list,$type_map[$val]);
  }
  //浏览器提供信息坚持
  $allow_mime_list = array_unique($allow_mime_list);
  if(!in_array($file[&#39;type&#39;],$allow_mime_list)){
    echo &#39;不支持该图片格式&#39;;
    return false;
  }
  //php自身检查
  $file_mime = new Finfo(FILEINFO_MIME_TYPE);
  $mime = $file_mime->file($file[&#39;tmp_name&#39;]);
  if(!in_array($mime,$allow_mime_list)){
    echo &#39;不支持该图片格式&#39;;
    return false;
  }
  //目录存储
  $up_loadpath = &#39;./&#39;;
  $sub_dir = date(&#39;Ymdh&#39;);
  if(!is_dir($up_loadpath.$sub_dir)){
    mkdir($up_loadpath.$sub_dir);
  }
  $prefix = &#39;bee_&#39;;
  $name = uniqid($prefix,true).$ext;
  if(move_uploaded_file($file[&#39;tmp_name&#39;],$up_loadpath.$sub_dir.$name)){
    echo &#39;上传成功&#39;;
    return $name;
  }else{
    echo &#39;上传失败&#39;;
    return false;
  }
}
Copy after login

I hope this article will be useful to everyone in PHP programming. helped.

For more detailed PHP file upload operation examples and related articles, please pay attention to the PHP Chinese website!

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 the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

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,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

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.

See all articles