Detailed explanation of file upload in php
May 30, 2018 am 11:29 AMHave you really mastered php file upload technology? This article has compiled relevant information on PHP file uploading for everyone. It has certain reference value. Interested friends can refer to it.
First of all, let me state that this chapter has a lot of content and is relatively difficult. , you have to have an attitude of fighting with yourself. Don’t miss the subtleties, practice more and more is the way to go.
Learning is like climbing a mountain. You have to do it step by step. First, set a small goal for yourself, and then continue to climb higher and higher, and finally reach the top.
Please consider the above two pieces of advice carefully
1. Description of my preparations.
Editor: sublime text3 (Which editor you use depends on your preference)
Server build: Use phpstudy2014 to build the server. The server file is stored in the www file on the D drive of my computer. (Installing phpstudy will automatically generate the www file, you decide which disk to install it on). Run phpstudy and enter localhost in the browser address bar to access files on the server.
The process of uploading files: The browser uploads the file on the client, click submit, the file is sent to a php file in the server for processing, and the php uploads the file Save the file to the server.
2. Create the form
Please see my html code
1. application/x-www-form-urlencoded: Form data is encoded as name/value pairs. This is a standard encoding format.
2. multipart/form-data: Form data is encoded as a message, and each control on the page corresponds to a part of the message.
3. text/plain: The form data is encoded in plain text, without any controls or formatting characters.
Supplement (just take a look): The enctype attribute of ORM is the encoding method. There are two commonly used ones: application/x-www-form-urlencoded and multipart/form-data. The default is application/x-www-form. -urlencoded. When the action is get, the browser uses the x-www-form-urlencoded encoding method to convert the form data into a string (name1=value1&name2=value2...), and then appends the string to the end of the url, splits it with ?, and loads it. this new url. When the action is post, the browser encapsulates the form data into the http body and then sends it to the server. If there is no type=file control, just use the default application/x-www-form-urlencoded. But if there is type=file, multipart/form-data will be used. The browser will divide the entire form into control units, and add Content-Disposition (form-data or file), Content-Type (default is text/plain), name (control name) and other information to each part, and Add delimiter (boundary).
In short, remember two sentences: if there is type=file in the input tag, then enctype=multipart/form-data. If there is no type=file, application/x-www-form-urlencoded is generally used.
When uploading files, the data must undergo certain transformations before they can be uploaded to the server. The difference between application/x-www-form-urlencoded and multipart/form-data is the conversion encoding method.
3. Create a php file to process the uploaded files.
FILES["myfile"]["error"]=1 The uploaded file exceeds the server limit, such as exceeding the server space size. _FILES["myfile"]["error"]=2 exceeds the browser limit for uploading $_FILES["myfile"]["error"]=3 Only part of the file is uploaded
Upload limit
Normally, the server usually limits the size or type of files uploaded by the server. We add restrictions on the uploaded file code based on the above php code.
First familiarize yourself with the usage of several functions:
explode()The function is used to split strings. For example: explode(“.”,”aaa.HTML”) is to divide this at the position of the dot. The string is divided into two strings, "aaa" and "HTML", and these two strings are stored in the same array in order.
end()Get the value of the last element in the array.
in_array() Search for an element in the array to see if it exists. It returns true if it exists and false if it does not exist.
<?php //第一步:明確服務(wù)器規(guī)定上傳至服務(wù)器的文件類型。這里我們只允許上傳以下類型的圖片。 $allowedExts = array("gif", "jpeg", "jpg", "png");// 允許上傳的圖片后綴 //第二部:獲取上傳的文件名稱,通過explorde()函數(shù)將其分割成字符串形式的數(shù)組。 $temp = explode(".", $_FILES["myfile"]["name"]); echo $_FILES["file"]["size"]; $extension = end($temp); // end函數(shù)用于獲取數(shù)組中最后一個(gè)元素的值。 //第三步:列出上傳文件需要滿足的條件 if ((($_FILES["myfile"]["type"] == "image/gif") || ($_FILES["myfile"]["type"] == "image/jpeg") || ($_FILES[myfile"]["type"] == "image/jpg") || ($_FILES["myfile"]["type"] == "image/pjpeg") || ($_FILES["myfile"]["type"] == "image/x-png") || ($_FILES["myfile"]["type"] == "image/png")) && ($_FILES["myfile"]["size"] < 204800) // 小于 200 kb && in_array($extension, $allowedExts)) //in_array表示在$allowedExts數(shù)組中查找$extension這個(gè)字符串 { if ($_FILES["myfile"]["error"] > 0) { echo "錯(cuò)誤:: " . $_FILES["myfile"]["error"] . "<br>"; //舉個(gè)例子服務(wù)器空間不足,文件只能上傳部分就會(huì)出現(xiàn)錯(cuò)誤。 } else { echo "上傳文件名: " . $_FILES["myfile"]["name"] . "<br>"; echo "文件類型: " . $_FILES["myfile"]["type"] . "<br>"; echo "文件大小: " . ($_FILES["myfile"]["size"] / 1024) . " kB<br>"; echo "文件臨時(shí)存儲(chǔ)的位置: " . $_FILES["myfile"]["tmp_name"] . "<br>"; } } else { echo "非法的文件格式"; } ?>
4. Save the uploaded file
After the file is uploaded, it is saved in a temporary location. It will disappear when the script ends. If we want to save it permanently on the server, we need to save it in another location.
. file_exists("upload/" . FILES["file"]["name"]) checks whether the file or directory exists. .moveuploadedfile(_FILES["file"]["tmp_name"], "upload/" . $_FILES["myfile"]["name"]);Move the uploaded file from the temporary location to the server space.
<?php //第一步:明確服務(wù)器規(guī)定上傳至服務(wù)器的文件類型。這里我們只允許上傳以下類型的圖片。 $allowedExts = array("gif", "jpeg", "jpg", "png");// 允許上傳的圖片后綴 //第二部:獲取上傳的文件名稱,通過explorde()函數(shù)將其分割成字符串形式的數(shù)組。 $temp = explode(".", $_FILES["myfile"]["name"]); echo $_FILES["myfilefile"]["size"]; $extension = end($temp); // end函數(shù)用于獲取數(shù)組中最后一個(gè)元素的值。 //第三步:列出上傳文件需要滿足的 if ((($_FILES["myfile"]["type"] == "image/gif") || ($_FILES["myfile"]["type"] == "image/jpeg") || ($_FILES["myfile"]["type"] == "image/jpg") || ($_FILES["myfile"]["type"] == "image/pjpeg") || ($_FILES["myfile"]["type"] == "image/x-png") || ($_FILES["myfile"]["type"] == "image/png")) && ($_FILES["myfile"]["size"] < 204800) // 小于 200 kb && in_array($extension, $allowedExts))//in_array表示在$allowedExts數(shù)組中查找$extension這個(gè)字符串 { if ($_FILES["myfilefile"]["error"] > 0) { echo "錯(cuò)誤:: " . $_FILES["myfile"]["error"] . "<br>"; } else { echo "上傳文件名: " . $_FILES["myfile"]["name"] . "<br>"; echo "文件類型: " . $_FILES["myfile"]["type"] . "<br>"; echo "文件大小: " . ($_FILES["myfile"]["size"] / 1024) . " kB<br>"; echo "文件臨時(shí)存儲(chǔ)的位置: " . $_FILES["myfile"]["tmp_name"] . "<br>"; // 判斷當(dāng)期目錄(即www文件夾中)下的 upload 目錄(自己創(chuàng)建,名字自?。┦欠翊嬖谠撐募? // 如果沒有 upload 目錄,你需要?jiǎng)?chuàng)建它,upload 目錄權(quán)限為 777 if (file_exists("upload/" . $_FILES["myfile"]["name"])) { echo $_FILES["myfile"]["name"] . " 文件已經(jīng)存在。 "; } else { // 如果 upload 目錄不存在該文件則將文件上傳到 upload 目錄下 move_uploaded_file($_FILES["myfile"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);// echo "文件存儲(chǔ)在: " . "upload/" . $_FILES["myfile"]["name"]; } } } else { echo "非法的文件格式"; } ?>
The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
How to combine two photos of the front and back of an ID card into one picture using PHP
PHP uses SWOOLE extension to implement scheduled synchronization of MySQL data
##PHP summary of object knowledge
The above is the detailed content of Detailed explanation of file upload in php. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

The steps to install PHP8 on Ubuntu are: 1. Update the software package list; 2. Install PHP8 and basic components; 3. Check the version to confirm that the installation is successful; 4. Install additional modules as needed. Windows users can download and decompress the ZIP package, then modify the configuration file, enable extensions, and add the path to environment variables. macOS users recommend using Homebrew to install, and perform steps such as adding tap, installing PHP8, setting the default version and verifying the version. Although the installation methods are different under different systems, the process is clear, so you can choose the right method according to the purpose.

PHPisaserver-sidescriptinglanguageusedforwebdevelopment,especiallyfordynamicwebsitesandCMSplatformslikeWordPress.Itrunsontheserver,processesdata,interactswithdatabases,andsendsHTMLtobrowsers.Commonusesincludeuserauthentication,e-commerceplatforms,for

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.

How to start writing your first PHP script? First, set up the local development environment, install XAMPP/MAMP/LAMP, and use a text editor to understand the server's running principle. Secondly, create a file called hello.php, enter the basic code and run the test. Third, learn to use PHP and HTML to achieve dynamic content output. Finally, pay attention to common errors such as missing semicolons, citation issues, and file extension errors, and enable error reports for debugging.

The "undefinedindex" error occurs because a key that does not exist in the array is accessed. Solutions include: 1. Use isset() to check whether the key exists, which is suitable for processing user input; 2. Use array_key_exists() to determine whether the key is set, and it can be recognized even if the value is null; 3. Use the empty merge operator?? to set the default value to avoid directly accessing undefined keys; in addition, you need to pay attention to common problems such as the spelling of form field names, the database result is empty, the array unpacking is not verified, the child keys are not checked in foreach, and the session_start() is not called.
