


PHP upload principle and operation implementation, PHP upload principle_PHP tutorial
PHP upload principle and operation implementation, PHP upload principle
Regarding the function library for PHP upload files, there are many well-packaged libraries on the Internet, and you can use them directly.
This article only talks about the principle of uploading and simple uploading operations. Old birds will ignore it ^_^~
There are also some security judgments, such as: the server restricts the ability to receive image-type files, and the client maliciously changes the suffix of the virus file to a file that matches the image type for uploading.
(For example, single file upload, the principle of multiple files remains the same, but there are a few more tricks)
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang ="en">
<head>
<meta http-equiv="Content-Type" content="text/ html;charset=UTF-8">
<title>upload filestitle>
head>
<body>
<form action="upload.php" enctype="multipart/form- data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="10000" />
Upload file: <input type="file" name=" file"/>
<input type="submit" value="upload" />
form>
body>
html>
1. Form tag enctype attribute
In the form, enctype="multipart/form-data" is the MIME encoding used to set the form.
By default, this encoding format is application/x-www-form-urlencoded and cannot be used for file upload;
It can only be completed if multipart/form-data is used and the submission method is Post transfer file data.
2. MAX_FILE_SIZE hidden field
MAX_FILE_SIZE The hidden field (unit is bytes) must be placed before the file input field, and its value is the maximum size of the received file. This is a recommendation for browsers, PHP will also check this.
This setting can be easily bypassed on the browser side, so don't expect to use this feature to block large files. (However, in view of friendliness, it is better to add this item to the form, because it can avoid the trouble of users spending time waiting to upload large files only to find that the file is too large and the upload failed.)
upload.php
<?<span>php </span><span>print_r</span>(<span>$_FILES</span><span>); </span>?>
We can see:
<span>Array</span><span> ( [</span><span>file</span>] => <span>Array</span><span> ( [name] </span>=> 照片文件.<span>jpg [type] </span>=> image/<span>jpeg [tmp_name] </span>=> F:\wamp\tmp\php41BB.<span>tmp [error] </span>=> 0<span> [size] </span>=> 73886<span> ) )</span>
3. Application of global variable $_FILES
$_FILES['file']['name'] is the original file name of the uploaded file
$_FILES['file']['type'] is the MIME type of the uploaded file
$_FILES['file']['size'] The size of the uploaded file, in bytes
$_FILES['file']['tmp_name'] The temporary file name () stored on the server after the file is uploaded
$_FILES['file']['error'] File upload error code
4. By default, the uploaded file will be saved in the temporary folder on the server, and its directory is set in php.ini
Some common settings in php.ini related to file upload:
file_uploads ; 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; That is the maximum size of files allowed to be uploaded. Default is 2M
post_max_size; refers to the maximum value that can be received through form POST to PHP, including all values in the form. The default is 8M
The following is the complete code for single file upload. Because it is written as I wish, the logic may be a bit messy. Understanding the principle is the most important thing.
<?<span>php </span><span>//</span><span>取得上传文件信息</span> <span>$fileName</span>=<span>$_FILES</span>['file']['name'<span>]; </span><span>$fileType</span>=<span>$_FILES</span>['file']['type'<span>]; </span><span>$fileError</span>=<span>$_FILES</span>['file']['error'<span>]; </span><span>$fileSize</span>=<span>$_FILES</span>['file']['size'<span>]; </span><span>$tempName</span>=<span>$_FILES</span>['file']['tmp_name'];<span>//</span><span>临时文件名 //定义上传文件类型</span> <span>$typeList</span> = <span>array</span>("image/jpeg","image/jpg","image/png","image/gif"); <span>//</span><span>定义允许的类型</span> <span>if</span>(<span>$fileError</span>>0<span>){ </span><span>//</span><span>上传文件错误编号判断</span> <span>switch</span> (<span>$fileError</span><span>) { </span><span>case</span> 1: <span>$message</span>="上传的文件超过了php.ini 中 upload_max_filesize 选项限制的值。"<span>; </span><span>break</span><span>; </span><span>case</span> 2: <span>$message</span>="上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。"<span>; </span><span>break</span><span>; </span><span>case</span> 3: <span>$message</span>="文件只有部分被上传。"<span>; </span><span>break</span><span>; </span><span>case</span> 4: <span>$message</span>="没有文件被上传。"<span>; </span><span>break</span><span>; </span><span>case</span> 6: <span>$message</span>="找不到临时文件夹。"<span>; </span><span>break</span><span>; </span><span>case</span> 7: <span>$message</span>="文件写入失败"<span>; </span><span>break</span><span>; </span><span>case</span> 8: <span>$message</span>="由于PHP的扩展程序中断了文件上传"<span>; </span><span>break</span><span>; } </span><span>exit</span>("文件上传失败:".<span>$message</span><span>); } </span><span>if</span>(!<span>is_uploaded_file</span>(<span>$tempName</span><span>)){ </span><span>//</span><span>判断是否是POST上传过来的文件</span> <span>exit</span>("不是通过HTTP POST方式上传上来的"<span>); }</span><span>else</span><span>{ </span><span>if</span>(!<span>in_array</span>(<span>$fileType</span>, <span>$typeList</span><span>)){ </span><span>exit</span>("上传的文件不是指定类型"<span>); }</span><span>else</span><span>{ </span><span>if</span>(!<span>getimagesize</span>(<span>$tempName</span><span>)){ </span><span>//</span><span>避免用户上传恶意文件,如把病毒文件扩展名改为图片格式</span> <span>exit</span>("上传的文件不是图片"<span>); } } </span><span>if</span>(<span>$fileSize</span>>100000<span>){ </span><span>//</span><span>对特定表单的上传文件限制大小</span> <span>exit</span>("上传文件超出限制大小"<span>); }</span><span>else</span><span>{ </span><span>//</span><span>避免上传文件的中文名乱码</span> <span>$fileName</span>=<span>iconv</span>("UTF-8", "GBK", <span>$fileName</span>);<span>//</span><span>把iconv抓取到的字符编码从utf-8转为gbk输出</span> <span>$fileName</span>=<span>str_replace</span>(".", <span>time</span>().".", <span>$fileName</span>);<span>//</span><span>在图片名称后加入时间戳,避免重名文件覆盖</span> <span>if</span>(<span>move_uploaded_file</span>(<span>$tempName</span>, "uploads/".<span>$fileName</span><span>)){ </span><span>echo</span> "上传文件成功!"<span>; }</span><span>else</span><span>{ </span><span>echo</span> "上传文件失败"<span>; } } } </span>?>
5. Some common functions for uploading files in PHP: (I won’t post the specific usage, just read the API documentation yourself ^_^)
file_exists Check whether the file or directory exists
is_uploaded_file Determine whether the file is uploaded via HTTP POST
move_uploaded_file Move the uploaded file to a new location
is_writable Determine whether the given file name is writable
iconv Character encoding conversion
str_replace String replacement (change file name, prevent duplicate names)
getimagesize Check whether it is an image file (other types of files can be detected even if the suffix name is changed)
What is implemented separately is to implement the login log and the operation log, customize the number of two functions, and DO these two functions respectively when the user logs in, adds, modifies and deletes. The information is recorded in the database table.
Don’t be so troublesome. There are many plug-ins for jquery that can realize the style of uploading file progress. You can use it
ps: Since you are such a personality, I will tell you the principle of implementation. The specific details are yourselves. Go ahead and do it.
Ordinary page access is all synchronous, that is, request-->feedback, and the progress bar requires real-time data, so ordinary pages cannot achieve this function, and you need to use asynchronous Ajax cycles to obtain progress data. The source of this data is of course sent by the server. This encounters a serious problem. PHP cannot obtain the status of the file transfer process. Fortunately, the founder of PHP wrote an APC extension (in addition An extension is uploadprogress), using the extended syntax, adding ajax, and using js to operate the DOM object of the page, the progress bar is realized.
You understand the principle, but it is difficult for you to make it, hey.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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

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

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,

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.

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

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.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7
