Home Backend Development PHP Tutorial Detailed explanation of the application and principle of php file upload_PHP tutorial

Detailed explanation of the application and principle of php file upload_PHP tutorial

Jul 13, 2016 am 10:50 AM
php post upload several principle and application Skill document of Know form Detailed explanation

You must know several tricks to upload files in php. One must be the data posted by the form, then accepted by php move_uploaded_file, and then saved to the specified path on the server.

1.form tag enctype attribute.

2.$_FILES system function. //Convert the uploaded content into an array.

3.move_uploaded_file function. //Move the uploaded files stored in the cache folder to the specified folder.

4.is_uploaded_file function. //Determine whether it exists.

------------------------------------------

1.form tag

Format:


       

2.$_FILES system function
$_FILES['name'] //The original file name of the file uploaded by the client.
$_FILES['type'] //MIME type of file, such as: "image/gif"
$_FILES['size'] //Upload file size in bytes.
$_FILES['tmp_name'] //Temporary file name, usually the default.
$_FILES['error'] //Upload related situation code (0: Success, 1: Exceeds the size set by php.ini. 2: Exceeds the size specified by the PHP file code. 3: Only part of the file is uploaded. 4: No file is uploaded .5: The uploaded file size is 0)

3.move_uploaded_file function
Function to move files to the target location after uploading
move_uploaded_file (temporary file, target location and file name;)

4.is_uploaded_file function
Function to determine the uploaded MIME type of file
is_uploaded_file(MIME);

------------------------------------------

Example:

The code is as follows Copy code
 代码如下 复制代码


  

 

Attention

1. enctype="multipart/form-data" must be specified in the form to let the server know that the file contains regular form information.
2. There must be a form area where the maximum length of the uploaded file can be set, that is, the maximum value of the uploaded file (calculated in bytes). It is a hidden value field, that is, max_file_size. By setting its Value (value), the uploaded file can be limited. size, to avoid the hassle of users spending time waiting for a large file to be uploaded only to discover that the file is too large. But generally others can bypass this value, so for safety reasons, it is best to configure the upload_max_filesize option in the php.ini file to set the size of the file upload. The default is 2M

The code is as follows Copy code
 代码如下 复制代码

function uploadfile($type,$name,$ext,$size,$error,$tmp_name,$targetname,$upload_dir)
{
    $MAX_SIZE = 2000000;
    $FILE_MIMES = array('image/pjpeg','image/jpeg','image/jpg','image/gif','image/png');
    $FILE_EXTS = array('.jpg','.gif','.png','.JPG','.GIF','.PNG');

    $file_path = $upload_dir.$targetname;
   
    if(!is_dir($upload_dir))
    {
        if(!mkdir($upload_dir))
            die("文件上传目录不存在并且无法创建文件上传目录");
        if(!chmod($upload_dir,0755))
            die("文件上传目录的权限无法设定为可读可写");
    }
   
    if($size>$MAX_SIZE)
        die("上传的文件大小超过了规定大小");

    if($size == 0)
        die("请选择上传的文件");

    if(!in_array($type,$FILE_MIMES) || !in_array($ext,$FILE_EXTS))
        die("请上传符合要求的文件类型");

    if(!move_uploaded_file($tmp_name, $file_path))
        die("复制文件失败,请重新上传");

    switch($error)
    {
        case 0:
            return ;
        case 1:
            die("上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值");
        case 2:
            die("上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值");
        case 3:
            die("文件只有部分被上传");
        case 4:
            die("没有文件被上传");
    }
}

function uploadfile($type,$name,$ext,$size,$error,$tmp_name,$targetname,$upload_dir)

{ $MAX_SIZE = 2000000; $FILE_MIMES = array('image/pjpeg','image/jpeg','image/jpg','image/gif','image/png');

$FILE_EXTS = array('.jpg','.gif','.png','.JPG','.GIF','.PNG');
 代码如下 复制代码

只需将


 

改成



$file_path = $upload_dir.$targetname;   If(!is_dir($upload_dir)) {           if(!mkdir($upload_dir)) die("The file upload directory does not exist and the file upload directory cannot be created"); If(!chmod($upload_dir,0755)) ​​​​​​die("The permissions of the file upload directory cannot be set to read and write"); }   If($size>$MAX_SIZE) ​​​​die("The uploaded file size exceeds the specified size"); if($size == 0)            die("Please select the file to upload"); if(!in_array($type,$FILE_MIMES) || !in_array($ext,$FILE_EXTS))             die("Please upload a file type that meets the requirements"); if(!move_uploaded_file($tmp_name, $file_path))               die("Failed to copy file, please upload again"); switch($error) { case 0: Return ; case 1:                     die("The uploaded file exceeds the value limited by the upload_max_filesize option in php.ini"); case 2: die("The size of the uploaded file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form"); case 3: die("Only part of the file was uploaded"); case 4:                die("No files were uploaded"); } }
How to upload multiple files? For example, upload 3 files at the same time
The code is as follows Copy code
Just replace changed to

Correspondingly, when calling this function, $_FILES['userfile']['name'][0] represents the relevant file information of the first file, and so on, and the same for others.

Some php performance configurations, we can modify them if necessary

max_execution_time = 30; The maximum time value (seconds) for each PHP page to run, the default is 30 seconds
max_input_time = 60; The maximum time required for each PHP page to receive data, the default is 60 seconds
memory_limit = 128m; The maximum memory consumed by each PHP page, the default is 128M. If it feels too small, you can set it larger. 128 is enough.
max_execution_time = 600
max_input_time = 600
upload_max_filesize = 32m
post_max_size = 32m

If the file size is limited we can solve it as follows

Open php.ini and first find

file_uploads = on ; Switch whether to allow file uploads via HTTP. The default is ON

upload_tmp_dir; Files are uploaded to the server where temporary files are stored. If not specified, the system default temporary folder will be used

upload_max_filesize = 8m; Wangwen business, that is, the maximum value of the file size allowed to be uploaded. Default is 2M

post_max_size = 8m; refers to the maximum value that can be received through POST to PHP through the form, including all values ​​in the form. The default is 8M

Generally, after setting the above four parameters, uploading a file of

But if you want to upload a large file >8M, it will definitely work if you only set the above four items.


Further configure the following parameters

max_execution_time = 600; The maximum time value (seconds) for each PHP page to run, the default is 30 seconds

max_input_time = 600; The maximum time required for each PHP page to receive data, the default is 60 seconds

memory_limit = 8m; The maximum memory consumed by each PHP page, the default is 8M

After modifying the above parameters, you can upload large files under normal circumstances allowed by the network

max_execution_time = 600
max_input_time = 600
memory_limit = 32m
file_uploads = on
upload_tmp_dir = /tmp
upload_max_filesize = 32m
post_max_size = 32m

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632639.htmlTechArticleYou must know several tricks to upload files in php. One must be to post the data in the form, and then move_uploaded_file by php After accepting it, save it to the specified path on the server. ...
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