search
HomeBackend DevelopmentPHP TutorialUpload multiple images in PHP

Upload multiple images in PHP

Feb 29, 2024 pm 06:00 PM
php programmingBackend Development

php Xiaobian Yuzai will introduce you how to upload multiple images in PHP. In website development, it is often necessary to implement the function of batch uploading images. In order to improve user experience and efficiency, uploading multiple images is a common requirement. PHP provides a wealth of functions and technologies to implement this function, including using forms, processing uploaded files, processing multiple files in a loop, etc. Through the guidance of this article, you will learn how to easily upload multiple images in PHP to add more interactive and creative elements to your website.

To make this possible, we need to specify the form action in our HTML file or section depending on how you structure your code base, and then use a built-in function to handle that action.

In this article, we will learn how to upload multiple images in PHP, which provides us with the ability to specify the required files from a form input, process all user-selected files, and upload or move to the desired location context.

Learn about form operations and $_FILES

for multiple file uploads in PHP

When the user puts any input into the HTML form, we use the POST method to send any input (from text to file) to the server side where our PHP application lives.

<fORM method=&#39;post&#39; action=&#39;&#39; enctype=&#39;multipart/form-data&#39;>

enctype='multipart/form-data' part specifies the encoding method of the form data, which is required when we use file upload in the form.

For file upload we need to enter the type file and specify the name (can be any name you decide) for the file.

<input type="file" name="file" id="file">

For multiple file uploads, we still need the input type file, but now with a different specified name file[] and the added attribute multiple. Adding [] indicates that the input field can handle multiple files.

<input type="file" name="files[]" multiple/>

On the server side, the global variable $_FILES is an associative array that contains files uploaded via the Http POST method, allowing us to handle the files appropriately.

<?php

$_FILES["files"]

Upload multiple images in PHP using move_uploaded_file()

Now that we understand the basics, we need to upload multiple files. Let's create a PHP form to upload multiple images.

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Multiple Image Upload</title>
</head>

<body>
<form method="post" enctype="multipart/form-data" name="formUploadFile">
<label>Select image(s) to upload:</label>
<input type="file" name="files[]" multiple="multiple" />
<input type="submit" value="Upload File" name="imgSubmit" />
</form>
<?php
if (isset($_POST["imgSubmit"])) {
$Upload multiple images in PHPs = [];
$uploadedFiles = [];
$extension = array("jpeg", "jpg", "png");
$UploadFolder = "images";

$counter = 0;

foreach ($_FILES["files"]["tmp_name"] as $key => $tmp_name) {
$temp = $_FILES["files"]["tmp_name"][$key];
$name = $_FILES["files"]["name"][$key];

if (empty($temp)) {
break;
}

$counter++;
$UploadOk = true;

$ext = pathinfo($name, PATHINFO_EXTENSION);
if (in_array($ext, $extension) == false) {
$UploadOk = false;
array_push($Upload multiple images in PHPs, $name . " isn&#39;t an image.");
}

if ($UploadOk == true) {
move_uploaded_file($temp, $UploadFolder . "/" . $name);
array_push($uploadedFiles, $name);
}
}

if ($counter > 0) {
if (count($Upload multiple images in PHPs) > 0) {
echo "<b>Errors:</b>";
echo "<br/><ul>";
foreach ($Upload multiple images in PHPs as $Upload multiple images in PHP) {
echo "<li>" . $Upload multiple images in PHP . "</li>";
}
echo "</ul><br/>";
}

if (count($uploadedFiles) > 0) {
echo "<b>Uploaded Files:</b>";
echo "<br/><ul>";
foreach ($uploadedFiles as $fileName) {
echo "<li>" . $fileName . "</li>";
}
echo "</ul><br/>";

echo count($uploadedFiles) . " iamge(s) are successfully uploaded.";
}
} else {
echo "Please, Select image(s) to upload.";
}
}
?>
</body>

</html>

Check whether the $_POST[] variable is set using the isset() function, initialize important variables, and set the extension required for file upload.

if (isset($_POST["imgSubmit"])) {
$Upload multiple images in PHPs = [];
$uploadedFiles = [];
$extension = array("jpeg", "jpg", "png");
$UploadFolder = "images";

After that we loop through the multiple images that have been processed via the $_FILES[] variable and then check the extension using pathinfo() and if true we move the image to the specified Folder $UploadFolder Use the move_uploaded_file() function and push the name of the image to the $uploadedFiles variable.

foreach ($_FILES["files"]["tmp_name"] as $key => $tmp_name) {
$temp = $_FILES["files"]["tmp_name"][$key];
$name = $_FILES["files"]["name"][$key];

if (empty($temp)) {
break;
}

$counter++;
$UploadOk = true;

$ext = pathinfo($name, PATHINFO_EXTENSION);
if (in_array($ext, $extension) == false) {
$UploadOk = false;
array_push($Upload multiple images in PHPs, $name . " isn&#39;t an image.");
}

if ($UploadOk == true) {
move_uploaded_file($temp, $UploadFolder . "/" . $name);
array_push($uploadedFiles, $name);
}
}

Finally, we show the existing Upload multiple images in PHPs and the uploaded files.

if ($counter > 0) {
if (count($Upload multiple images in PHPs) > 0) {
echo "<b>Errors:</b>";
echo "<br/><ul>";
foreach ($Upload multiple images in PHPs as $Upload multiple images in PHP) {
echo "<li>" . $Upload multiple images in PHP . "</li>";
}
echo "</ul><br/>";
}

if (count($uploadedFiles) > 0) {
echo "<b>Uploaded Files:</b>";
echo "<br/><ul>";
foreach ($uploadedFiles as $fileName) {
echo "<li>" . $fileName . "</li>";
}
echo "</ul><br/>";

echo count($uploadedFiles) . " image(s) are successfully uploaded.";
}
} else {
echo "Please, Select image(s) to upload.";
}

PHP file served to the browser.

在 PHP 中上传多个图像

Select an image and upload the image.

在 PHP 中上传多个图像

Then, the uploaded file is displayed.

Upload multiple images in PHP

Uploaded image:

Upload multiple images in PHP

If the file you select is not an image, an Upload multiple images in PHP will appear.

Upload multiple images in PHP

The above is the detailed content of Upload multiple images in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:编程网. If there is any infringement, please contact admin@php.cn delete
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.

How often should you regenerate session IDs?How often should you regenerate session IDs?Apr 23, 2025 am 12:03 AM

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!