Server-side file upload can be easily implemented using PHP. There are various ways available to upload image to server and display images on the webpage. Generally, in a dynamic web application, the uploaded image is stored in a directory of the server and the file name is inserted in the database. Later, the images are retrieved from the server based on the file name stored in the database and display on the web page.
The image can be uploaded directly to the database without storing on the server. But it will increase the database size and web page load time. So, it’s always a good idea to upload images to the server and store file names in the database. In this tutorial, we will show you the entire process to upload and store the image file in MySQL database using PHP.
The example code demonstrates the process to implement the file upload functionality in the web application and the following functionality will be implemented.
To store the image file name a table need to be created in the database. The following SQL creates an images
table with some basic fields in the MySQL database.
CREATE TABLE `images` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`file_name` varchar(255) NOT NULL,
`uploaded_on` datetime NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT 1,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The dbConfig.php
file is used to connect and select the MySQL database. Specify the database hostname ($dbHost
), username ($dbUsername
), password ($dbPassword
), and name ($dbName
) as per your MySQL credentials.
<?php
// Database configuration
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName = "codexworld_db";
// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>
Create an HTML form to allow the user to choose a file they want to upload. Make sure <form> tag contains the following attributes.
Also, make sure <input> tag contains type="file"
attribute.
<form action="upload.php" method="post" enctype="multipart/form-data"> Select Image File to Upload: <input type="file" name="file"> <input type="submit" name="submit" value="Upload"> </form>
The file upload form will be submitted to the upload.php
file to upload image to the server.
The upload.php
file handles the image upload functionality and shows the status message to the user.
<?php
// Include the database configuration file
include_once 'dbConfig.php';
$statusMsg = '';
// File upload directory
$targetDir = "uploads/";
if(isset($_POST["submit"])){
if(!empty($_FILES["file"]["name"])){
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif');
if(in_array($fileType, $allowTypes)){
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
// Insert image file name into database
$insert = $db->query("INSERT INTO images (file_name, uploaded_on) VALUES ('".$fileName."', NOW())");
if($insert){
$statusMsg = "The file ".$fileName. " has been uploaded successfully.";
}else{
$statusMsg = "File upload failed, please try again.";
}
}else{
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$statusMsg = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.';
}
}else{
$statusMsg = 'Please select a file to upload.';
}
}
// Display status message
echo $statusMsg;
?>
Now we will retrieve the uploaded images from the server based on the file names in the database and display images in the web page.
<?php
// Include the database configuration file
include 'dbConfig.php';
// Get images from the database
$query = $db->query("SELECT * FROM images ORDER BY uploaded_on DESC");
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$imageURL = 'uploads/'.$row["file_name"];
?> <img src="<?php echo $imageURL; ?>" alt="" /> <?php }
}else{ ?> <p>No image(s) found...</p> <?php } ?>
Create Dynamic Image Gallery with jQuery, PHP & MySQL
Here we have shown the most effective way to implement image upload functionality on the website. You can easily extend the file upload functionality as per your requirements. For providing the better user-interface you can integrate the Ajax File Upload functionality.
Upload multiple images using jQuery, Ajax and PHP
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
You are great bro
thanks lot how resizing image
Thank y.. this help me so much!
thanks bro
thanks a lot
great example . thanks a lot
Thanks a lot, really helpful.
Thanks so much for this code worked
can you piz do one like this but have a img title at the top of the img thanks
Thanks for help Us
thank you
great. thanks.
Thanks
Best web 🙂
Thank sir, for your kindness
Thank you, good share.
Thanks.
New knowledge accumulated.
Really useful. God bless.
thanks, it works for me
thank sir ,this helpful site. very good
Thanks Dude you did a great job
thanks for help
please sir how to upload multi images to database????
Please provide script for two image uploading with two input field and text field through one submit button