PHP 8 Ajax Multiple Image Upload Example

03-Apr-2023

.

Admin

PHP 8 Ajax Multiple Image Upload Example

Hi Dev,

In this blog, I will give you how to upload multiple image in php 8 with ajax. In this tutorial PHP 8 multiple image uploading and storing tutorial with ajax and mysql database. In this tutorial, we will learn how to upload multiple images in MySQL Database using ajax.

Multiple image Upload in php 8 with ajax. I am going to show you about multiple image upload in php 8 using jquery ajax. this example will help you php 8 upload multiple image to database with jquery ajax. This article goes in detailed on how to upload multiple image in php 8 with ajax. Here, Creating a basic example of php 8 multiple image upload using jquery ajax.

I created simple form with file input. So you have to simple select image and then it will upload in "images" directory of this folder. So you have to simple follow bellow step and get multiple image upload in php 8 ajax application.

Here, I will give you full example for simply multiple image upload using php 8 jquery ajax as bellow.

Create Database


In this step you can create database `php_crud`.

Create `table_name` inside the database.

You can execute the following command to create the table columns to store the images in the database.

CREATE TABLE `user` (

`id` int(11) NOT NULL,

`image` varchar(255) NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Database Configuration

config.php

<?php

$servername = 'localhost';

$username = 'root';

$password = 'root';

$dbname = "php_crud";

$conn = mysqli_connect($servername,$username,$password,"$dbname");

if(!$conn){

die('Could not Connect MySql Server:' .mysql_error());

}

?>

index.php

<!doctype html>

<html lang="en">

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

<title>PHP 8 Upload Multiple Files Example</title>

<style>

.container {

max-width: 450px;

}

.imgGallery img {

padding: 8px;

max-width: 100px;

}

</style>

</head>

<body>

<div class="container mt-5">

<form method="post" enctype="multipart/form-data" class="mb-3" id="uploadForm">

<h3 class="text-center mb-5">Upload Multiple Images in PHP 8</h3>

<div class="user-image mb-3 text-center">

<div class="imgGallery">

<!-- Image preview -->

</div>

</div>

<div class="custom-file">

<input type="file" name="fileUpload[]" class="custom-file-input" id="chooseFile" multiple>

<label class="custom-file-label" for="chooseFile">Select file</label>

</div>

<button type="submit" name="submit" class="btn btn-primary btn-block mt-4">

Upload Files

</button>

</form>

<!-- Display response messages -->

<?php if(!empty($response)) {?>

<div class="alert <?php echo $response["status"]; ?>">

<?php echo $response["message"]; ?>

</div>

<?php }?>

</div>

<!-- jQuery -->

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>

<script>

$(document).ready(function (e) {

$("#uploadForm").on('submit',(function(e) {

e.preventDefault();

$.ajax({

url: "store.php",

type: "POST",

data: new FormData(this),

contentType: false,

cache: false,

processData:false,

success: function(data)

{

var data = JSON.parse(data);

var data = JSON.parse(data.data);

$('.imgGallery').empty();

$.each(data, function(index, val) {

$('.imgGallery').append('<img src="images/'+val+'">');

console.log(val);

});

},

error: function(error)

{

console.log(error);

}

});

}));

});

</script>

</body>

</html>

store.php

<?php

// Database

include 'config.php';

$uploadsDir = "images/";

$allowedFileType = array('jpg','png','jpeg');

// Velidate if files exist

if (!empty(array_filter($_FILES['fileUpload']['name']))) {

// Loop through file items

$images = [];

foreach($_FILES['fileUpload']['name'] as $id=>$val){

// Get files upload path

$fileName = $_FILES['fileUpload']['name'][$id];

$tempLocation = $_FILES['fileUpload']['tmp_name'][$id];

$targetFilePath = $uploadsDir . $fileName;

$fileType = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION));

$uploadOk = 1;

if(in_array($fileType, $allowedFileType)){

if(move_uploaded_file($tempLocation, $targetFilePath)){

$images[] = $fileName;

} else {

$response = array(

"status" => "alert-danger",

"message" => "File coud not be uploaded."

);

}

} else {

$response = array(

"status" => "alert-danger",

"message" => "Only .jpg, .jpeg and .png file formats allowed."

);

}

}

// Add into MySQL database

if(!empty($images)) {

$images = json_encode($images);

$q = "INSERT INTO user(image)

VALUES ('{$images}')";

$sql = mysqli_query($con, $q);

if($sql) {

$response = array(

"status" => "alert-success",

"message" => "Files successfully uploaded.",

"data" => $images

);

} else {

$response = array(

"status" => "alert-danger",

"message" => "Files coudn't be uploaded due to database error."

);

}

}

} else {

// Error

$response = array(

"status" => "alert-danger",

"message" => "Please select a file to upload."

);

}

echo json_encode($response);

?>

Now we are ready to run our example so run bellow command for quick run:

php -S localhost:8000

Now you can open bellow URL on your browser:

http://localhost:8000

It will help you....

#PHP 8

#PHP