search
HomeBackend DevelopmentPHP TutorialDetailed explanation of PHP file upload operation examples

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>

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 =

Persistently store temporary files

move_uploaded_file(src_url,goa_url)

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

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

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

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

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;]);

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

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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment