search
HomeBackend DevelopmentPHP TutorialIn-depth analysis of php upload files

In-depth analysis of php upload files

Mar 15, 2018 am 09:55 AM
phpdepthparse

This article mainly shares with you the in-depth analysis of PHP upload files. We have also shared many articles about PHP upload files with you before. I hope this article can help everyone.

1.phpUpload file configurationphp.iniConfiguration:

(1)file_uploads=on|off Determine PHP on the server Whether the script can accept file uploads.

2max_execution_time=integer PHP The maximum amount of time, in seconds, that a script can execute before registering a fatal error

.

3memory_limit=integer Settings The maximum memory that a script can allocate, in MB. This prevents runaway scripts from monopolizing server memory.

4

upload_max_filesize=integer : Set the maximum size of the uploaded file to MB is the unit. This directive must be smaller than

post_max_size

.

5

upload_tmp_dir=string Settings Uploaded files must be stored in a temporary location on the server before being processed, until the file is moved to its final destination.

6

post_max_size=integer : OK to pass POSTThe maximum size of the message that the method can accept, in MB as the unit

2.php

Upload related methods

1bool is_uploaded_file(string $filename)

Definition: is_uploaded_file() The function determines whether the specified file is uploaded through HTTP POST

Parameters $filename : $_FILES['file_img']['tmp_name'](Example)

Specifies the file to be checked: C:\Windows\Temp\php9632.tmp

(2)bool move_uploaded_file ( string $filename , string $destination )

Definition: move_uploaded_file () Function moves the uploaded file to a new location General and is_uploaded+_file()Method used together

Parameters $filename: $_FILES['file_img']['tmp_name'](example)

Specify the files to be moved : C:\Windows\Temp\php9632.tmp                                                                             ## $ DESTION

##:

DIRNAME (__file __). Ds.'uploads'.ds. $ _ Files ['file_img'] ['name'] (Example) Specify the location of the file to be moved:

D:\myWAP\myWeb \learn\php_upload\uploads\hm_g_img.jpg##3.phpUpload case: It is stipulated that only image files can be uploaded

##(

1

Necessary folder and file

2file_unload_select.php file is used for the HTMLBrowse selection, upload click:


##enctype = "multipart/form-data" Fixed Writing method, otherwise the file upload will fail

action = "url"

## method="post"

Generally upload is post


##(

3upload.php File is used to process uploaded files Determine the type of uploaded file and Move the file to the specified directory on the server:

//接收上传文件
print_r($_FILES);
define('DS',DIRECTORY_SEPARATOR);


//判断当前上传的文件是否为图片
$img_type_arr = array('image/png','image/jpeg','image/jpeg');

//for循环遍历数组 -- 第一方法判断是否为数组中的子项
for($i=0;$i<count($img_type_arr);$i++)
{
       if($img_type_arr[$i] != $_FILES[&#39;file_img&#39;][&#39;type&#39;] && ($i == count($img_type_arr)-1) )
       {
                echo ""
                exit;
       }
}



//数组方法array_in() -- 第二方法判断是否为数组中的子项
if(!is_uploaded_file($_FILES[&#39;file_img&#39;][&#39;tmp_name&#39;]))
{
      //如果临时文件不存在,则说明没有上传到临时文件夹
      echo  &#39;上传到临时文件夹失败&#39;;
}
else
{

   //echo &#39;上传到临时文件夹成功&#39;;
   $img_path = dirname(__FILE__).DS.&#39;uploads&#39;.DS.$_FILES[&#39;file_img&#39;][&#39;name&#39;];

   //echo $img_path;

   //进行移动文件到服务器地址
   if(@move_uploaded_file($_FILES[&#39;file_img&#39;][&#39;tmp_name&#39;],$img_path))
   {
        //显示图片
        echo "<img  src="/static/imghwm/default1.png"  data-src=".$img_path."  class="lazy"   / alt="In-depth analysis of php upload files" >"
   }
   else
   {
        cho &#39;移动文件失败&#39;;

   }
}


4show_image.php Used to receive the image file path and display the successfully uploaded image:

$img_path = $_GET[&#39;url&#39;];

echo "";
(

5) The core of uploading is to use $_FILES sub-parameters, complete uploading and judgment :

Array ( [file_img] => Array ( [name] => news_001_01.jpg [type] => image/jpeg 
[tmp_name] => C:\Windows\Temp\php504D.tmp [error] => 0 [size] => 158360 ) )
Analysis:

$_FILES['file_img']['name'] : news_001_01.jpg

Upload file name$_FILES['file_img'][ 'type'] : image/jpeg

Type of uploaded file$_FILES['file_img'][' tmp_name '] : C:\Windows\Temp\ php504D.tmp

The storage path of the temporary file of the uploaded file$_FILES['file_img']['error '] : 0 , 1, 2, 3, 4

0 -& GT; ## Represents the file upload successfully

1 -& GT; The size of the file exceeds the agreed value (specified by PHP.ini) 2 ->

Indicates uploading the file The size exceeds the agreed value (HTMLspecified in the form) 3 ->

Indicates that the file is only partially Upload## 4 ->

means no files were uploaded

Related recommendations:

Native JS upload large file display progress bar php upload file code

php upload file code implement native JS upload large file display progress bar example

Simple code for php upload files

The above is the detailed content of In-depth analysis of php upload files. For more information, please follow other related articles on 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
What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

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

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),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment