Feb 20, 2023

How To upload multiple image files to the server at once using HTML & PHP Code

In the Following code we will try to upload multiple image files to the server at once to the "img" folder under the following conditions:

1-Use a random coding method to change the file name and prevent filename duplications.

2-If a filename already exists, change the name to avoid conflicts.

3-Show all images in separate DIVs after uploading, with their new names displayed underneath.

You can accomplish this using PHP and HTML. The HTML code will contain a form with an input field that accepts multiple image files. The PHP code will retrieve the uploaded images using the $_FILES superglobal and loop through each image, moving it to the specified "img" folder.

To prevent filename duplications, the code will generate a random name for each file using the uniqid() function. If a file with the same name already exists, the code will keep generating new names until it finds a unique one.

Finally, the code will display each uploaded image in a separate div with the new filename displayed underneath using the basename() function. Note that you'll need to ensure that the "img" folder exists and has the appropriate write permissions.

HTML Code:

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">    
    <title>Upload Images</title>
    <!-- <link rel="stylesheet" href="css/style.css">-->
</head>
<body>
<form method="POST" action="upload.php" enctype="multipart/form-data">
<input type="file" name="images[]" multiple>
<button type="submit" name="upload">Upload Images</button>
</form>
</body>
</html>

PHP file code:
/* upload.php */
<?php
if(isset($_POST['upload'])){
$images = $_FILES['images'];
$upload_dir = 'img/';
$uploaded = array();

foreach($images['name'] as $key=>$image){
$image_tmp = $images['tmp_name'][$key];
$image_name = $images['name'][$key];
$image_size = $images['size'][$key];
$image_ext = pathinfo($image_name, PATHINFO_EXTENSION);
$image_path = $upload_dir . uniqid() . '.' . $image_ext;

// Check if file already exists, change the name
while(file_exists($image_path)){
$image_path = $upload_dir . uniqid() . '.' . $image_ext;
}

// Upload the file
if(move_uploaded_file($image_tmp, $image_path)){
$uploaded[] = $image_path;
}
}

// Display uploaded images
foreach($uploaded as $image){
echo '<div><img src="'.$image.'"><br>New Name: '.basename($image).'</div>';
}
}
?>

No comments:

Post a Comment

Web Application Security for PHP Programmers: Best Practices and Techniques

Web application security is a critical concern for PHP programmers, and it's important to be well-versed in security practices to ensure...