This article mainly introduces two methods of php file upload in detail. Interested friends can refer to it
There are generally two ways to upload files:
Yes Two types:
1. Standard input form method, typically using $_FILES to receive;
2. Transmission in Base64 method, usually AJAX asynchronous upload.
The first
standard input form method is suitable for uploading large files and supports batches. Key sentences of html code:
<form enctype="multipart/form-data" method="post" action="upload.php""> <input type="file" name="id_pic[]" accept="image/*" class="form-control" multiple /> <input type="submit" value="上传 " /> </form>
Different names:
<form enctype="multipart/form-data" method="post" action="upload.php""> <input type="file" name="id_pic_1" accept="image/*" class="form-control" /> <input type="file" name="id_pic_2" accept="image/*" class="form-control" /> <input type="submit" value="上传 " /> </form>
Among them, enctype="multipart/form-data" is essential for file upload. In addition, type="file" sets the input type, and accept="image/*" specifies priority in uploading images (MIME reference manual). Multiple supports selecting multiple files at one time, and pic[] receives multiple files in the form of an array. The mobile terminal can also add the parameter capture="camera" to select the camera to take pictures and upload them.
Backend processing:
Get the uploaded files through $_FILES.
$files = $_FILES;
When transferring multiple files, if the names are different, the format of the returned $_FILES array will be different.
When the names are the same:
array(1) { ["id_pic"] => array(5) { ["name"] => array(2) { [0] => string(5) "1.jpg" [1] => string(5) "2.jpg" } ["type"] => array(2) { [0] => string(10) "image/jpeg" [1] => string(10) "image/jpeg" } ["tmp_name"] => array(2) { [0] => string(27) "C:\Windows\Temp\php7A7E.tmp" [1] => string(27) "C:\Windows\Temp\php7A7F.tmp" } ["error"] => array(2) { [0] => int(0) [1] => int(0) } ["size"] => array(2) { [0] => int(77357) [1] => int(56720) } } }
When the names are not the same:
array(2) { ["id_pic_1"] => array(5) { ["name"] => string(5) "1.jpg" ["type"] => string(10) "image/jpeg" ["tmp_name"] => string(27) "C:\Windows\Temp\phpBBEE.tmp" ["error"] => int(0) ["size"] => int(77357) } ["id_pic_2"] => array(5) { ["name"] => string(5) "2.jpg" ["type"] => string(10) "image/jpeg" ["tmp_name"] => string(27) "C:\Windows\Temp\phpBBEF.tmp" ["error"] => int(0) ["size"] => int(56720) } }
In the pair $ When _FILES performs foreach traversal, the previous output format is not very convenient. The latter can be traversed directly. We can write a method for unified conversion:
function dealFiles($files) { $fileArray = array(); $n = 0; foreach ($files as $key=>$file){ if(is_array($file['name'])) { $keys = array_keys($file); $count = count($file['name']); for ($i=0; $i<$count; $i++) { $fileArray[$n]['key'] = $key; foreach ($keys as $_key){ $fileArray[$n][$_key] = $file[$_key][$i]; } $n++; } }else{ $fileArray = $files; break; } } return $fileArray; }
Okay, I talked about how the backend processes the received $_FILES array and converts it into a unified format. The next main tasks are:
1. Check whether the uploaded file is illegal;
2. Check whether the uploaded file exceeds the size;
3. Check whether the saved path exists and whether it is writable;
4. File renaming;
A very important function is used in the upload process: move_uploaded_file(filename, $destination) to perform file moving operations. Move $_FILES['id_pic']['tmp_name'] to the new path. Of course, before moving, you can use is_uploaded_file($_FILES['id_pic']['tmp_name']) to determine whether the file is uploaded normally.
Multiple file upload is a circular method using move_uploaded_file() multiple times to perform the move operation.
The second type
is mainly about uploading pictures.
Use the change event of the input to process the image (such as compression) with canvas, and then send the file stream to the backend via ajax.
The basic principle is to render the image through canvas, and then compress and save it into a base64 string through the toDataURL method (can be compiled into a jpg format image).
Back-end processing:
The back-end will eventually receive the base64 string sent by the front-end, and then process the string into an image. Specifically, please use the keyword base64 to image development language for Google|Baidu. There is a base64Len in the result generated by the front end, which is the length of the string, and the back end should check to confirm whether the submission is complete.
//php示例: $img = base64_decode($_POST['img']); $img = imagecreatefromstring($img);
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
phpMethods and simple analysis of connecting to oracle database
PHP packaging MSSql operation class and complete example analysis
phpCore steps and brief analysis of connecting to Oracle database
The above is the detailed content of Two ways to implement file upload in php. For more information, please follow other related articles on the PHP Chinese website!

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.

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.

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.

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.

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.

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.

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

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.


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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Atom editor mac version download
The most popular open source editor

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
