Upload Multiple Image in PHP and Mysql

Abhigyan Singh 09th Sep 2020

In this PHP tutorial, you will learn how to upload multiple images using PHP and Mysql. Mysql is used to store uploaded images. You can display that stored Image in frontend.

Here users can upload multiple images at a time. Currently, this feature is very necessary for web projects. Image and Images are important parts of any web-based project. Upload pictures are important for social media sites. Here I use Mysql to store all the updated images.

Steps are given below:

dbConfig.php

<?php
define ("DB_HOST", "localhost"); // set database host
define ("DB_USER", ""); // set database user
define ("DB_PASS",""); // set database password
define ("DB_NAME",""); // set database name

$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");
?>

Index.php

<form id="frm" method="post" enctype="multipart/form-data" action='processImage.php'>
Upload your image
<div id='imgLoading' style='display:none'><img src="loading.gif" alt="Uploading...."/></div>
<div id='ingLoadButton'>
<input type="file" name="deskImg" id="deskImg" />
</div>
</form>

processImage.php

<?php

function getExtension($str)
{

$i = strrpos($str,".");
if (!$i) { return ""; }

$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}

$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['deskImg']['name'];
$size = $_FILES['deskImg']['size'];

if(strlen($name))
{
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $ext), 5).".".$ext;
$tmp = $_FILES['deskImg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysql_query("UPDATE members SET avatar='$actual_image_name' WHERE id='1'");

echo "<img src='images/".$actual_image_name."' class='displayImg'>";
}
else
echo "Fail upload folder with read access.";
}
else
echo "Image file size max 1 MB";
}
else
echo "Error in Invalid file format or Extension ..";
}

else
echo "Please select image to upload..!";

exit;
}

?>

Now you can make the necessary changes. and Enjoy uploading multiple images and pictures.

Authored By Abhigyan Singh

He is a continuous blogger and has blogged on different topic. He loves to surf Internet and always trying to get new Idea about new Technology and Innovations and sharing these great information to all the technology lovers.

Also on DiscussDesk