With the continuous development of the Internet, more and more websites need to support the multi-image upload function. For websites, while implementing the multi-image upload function, they also need to support the preview and delete functions, so as to better meet the needs of the Internet. User needs. This article will introduce how to use PHP to implement multiple image upload, preview and delete functions.
1. Implementation of the multi-image upload function
- HTML code
Create a form in the HTML code, add an input tag, and the type attribute is file, this tag allows the user to select the image to be uploaded, and an enctype attribute needs to be added with a value of "multipart/form-data", indicating that the form will be submitted using the multipart/form-data format.
- PHP code
The PHP code accepts image files submitted by the form and uploads the files to the specified directory on the server. Data processing and verification are also required. .
// 设置上传目录 $dir = './uploads/'; // 处理上传图片 if (isset($_FILES['image'])) { $image = $_FILES['image']; // 遍历上传的图片 foreach ($image['name'] as $key => $name) { // 获取图片扩展名 $ext = pathinfo($name, PATHINFO_EXTENSION); // 生成新文件名,避免文件名重复 $newFileName = uniqid() . '.' . $ext; // 将上传的图片移到目标目录 move_uploaded_file($image['tmp_name'][$key], $dir . $newFileName); // 将上传成功的文件名保存到数组中 $fileNames[] = $newFileName; } }
2. Implementation of the preview function
Firstly, the successfully uploaded images need to be displayed on the page. Here, a foreach loop is used to traverse the uploaded images, and the HTML img tag is used to display them.
<div> <?php foreach ($fileNames as $fileName) { ?> <img src="/static/imghwm/default1.png" data-src="./uploads/<?php echo $fileName ?>" class="lazy" alt="How to delete multiple image upload previews in PHP" > <?php } ?> </div>
The above code will display all successfully uploaded images, but this method cannot perform some interactive operations, such as mouse hovering, clicking, etc. Therefore, we also need to use JavaScript to achieve these effects. Here we use jQuery to quickly implement the corresponding functions.
- Display the delete button when the mouse hovers over it
Use CSS to set a delete button that displays when the mouse hovers over the image.
.delete-btn { position: absolute; top: 5px; right: 5px; width: 20px; height: 20px; cursor: pointer; background-color: #fff; border-radius: 50%; opacity: 0.7; visibility: hidden; transition: opacity ease-in-out 0.2s; } .image-container:hover .delete-btn { visibility: visible; }
- Perform the deletion operation when you click the delete button
After clicking the delete button, the corresponding image needs to be deleted from the server and removed from the HTML page . Here we use ajax to implement asynchronous deletion operations.
<div> <img class="image lazy" src="/static/imghwm/default1.png" data-src="./uploads/<?php echo $fileName ?>" alt="How to delete multiple image upload previews in PHP" > <div>">x</div> </div>
// 点击删除按钮时触发 $('.delete-btn').on('click', function() { var $container = $(this).closest('.image-container'); var fileName = $(this).data('filename'); // 发送异步请求删除服务器上的图片 $.ajax({ url: '/delete.php', type: 'POST', data: {fileName: fileName}, success: function(response) { // 移除页面中的图片 $container.remove(); } }); });
3. Implementation of the delete function
When the delete button is clicked, an asynchronous request is triggered to delete the corresponding image from the server. We can perform some checksum prompts before deletion and give corresponding prompt information when an error occurs.
- Delete Verification
Before deleting, we need to verify whether the image exists. If it does not exist, the deletion operation cannot be performed.
$file = $dir . $_POST['fileName']; if (file_exists($file)) { // 删除文件 unlink($file); echo 'success'; } else { echo '文件不存在'; }
- Delete prompt
We can use ajax to return the status code to the front end after the deletion fails or succeeds, and display the corresponding prompt information. Here is a simple and easy-to-use prompt box that uses the pop-up window component in Bootstrap.
<!-- 弹出窗口模板 --> <div> <strong>删除失败!</strong>文件不存在. <button> <span>×</span> </button> </div>
$.ajax({ url: '/delete.php', type: 'POST' data: {fileName: fileName}, success: function(response) { if (response === 'success') { // 显示删除成功提示 $('.delete-success').removeClass('hidden'); } else { // 显示删除失败提示 $('.delete-failed').removeClass('hidden'); } } });
So far, we have successfully implemented the multi-image upload, preview and deletion functions, and at the same time carried out corresponding verification and prompts. The above is just a brief introduction to the implementation. If you need to use these functions, you can make corresponding modifications and extensions according to your needs.
The above is the detailed content of How to delete multiple image upload previews in PHP. For more information, please follow other related articles on the PHP Chinese website!

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct


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

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.