How to Upload Image in PHP and Store in Folder and Database

How to Upload Image in PHP and Store in Folder and Database

Here in this tutorial, I will show you how you can upload image in the server. There are soo many ways to store an image in a server but here in this tutorial, we use PHP to control file system and MySQL database. We store images in the server directory and use MySQL database to trace those images. At last, we use data from our database to display those image.

An image can also be stored in a database but this will increase server load as well as database size. So as possible, it is not a good idea to store images in a database. Where server is designed to server file so it will serve image faster than a database.

To make it easier for you to flow the code, I have divided this coding into four parts.

  • Creating a database table
  • HTML form to upload an image.
  • Upload image to server using PHP and Store file name in the MySQL database.
  • Retrieve images from the database and display on the web page.

Create Database Table

To store the image file name we need to create a table in the database. Execute the following SQL and it will create 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) COLLATE utf8_unicode_ci NOT NULL,
 uploaded_on datetime NOT NULL,
 PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Files and folder we need here

  • uploads (folder)
  • config.php
  • index.php
  • upload.php

config.php

By using config.php file we connect our web page to our database so that we can store our image details into the database table. And later on, retrieve that image to display it on our webpage.

For a database connection, we need localhost name $dbHost, database user name $dbUsername, database password $dbPassword, and database name $dbName.

<?php
// Database configuration
$dbHost     = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName     = "codexworld";

// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

// Check connection
if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
}
?>

index.php

In this file, we write a code to make form. From which our user can upload their image. And also display uploaded images into our web page.

<!DOCTYPE html>
<html>
<head>
  <title>Upload Image</title>
</head>
<body>
  <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>
  <hr>

  <?php
  // Include the database configuration file
  include 'config.php';

  // Get images from the database
  $query = $db->query("SELECT file_name FROM images ORDER BY uploaded_on DESC");

  if($query->num_rows > 0){
      while($row = $query->fetch_assoc()){
          $imageURL = 'uploads/'.$row["file_name"];
  ?>
      <img src="<?= $imageURL; ?>" />
  <?php }} ?>
</body>
</html>

upload image layoutThe form coding from line 7 – 11 is used to send an image into upload.phpfile with a post method and we use enctype="multipart/form-data"because we are sending an image.

The coding line from 14 – 26 is used to display an image in a webpage just below the form.

upload.php

This file is used to get an image receives an image detail which is sent from index.php file. Then store the image in uploads folder at last store image details in MySQL database table.

<?php
// Include the database configuration file
include 'config.php';
$statusMsg = '';
$backlink = ' <a href="./">Go back</a>';

// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);

if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
    // Allow certain file formats
    $allowTypes = array('jpg','png','jpeg','gif','pdf');
    if (!file_exists($targetFilePath)) {
        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 <b>".$fileName. "</b> has been uploaded successfully." . $backlink;
                }else{
                    $statusMsg = "File upload failed, please try again." . $backlink;
                } 
            }else{
                $statusMsg = "Sorry, there was an error uploading your file." . $backlink;
            }
        }else{
            $statusMsg = "Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload." . $backlink;
        }
    }else{
            $statusMsg = "The file <b>".$fileName. "</b> is already exist." . $backlink;
        }
}else{
    $statusMsg = 'Please select a file to upload.' . $backlink;
}

// Display status message
echo $statusMsg;
?>
  • $statusMsgis used to store status message either it is success or failure on upload. Then at the end, we display that message.
  • $backlinkis used to go to the home page.
  • Line 13 if the statement means that the upload process will continue only if the user selects the image and then click the submit button.
  • In 15. We store the extension in an array which we allow our user to upload on the server.
  • 16. The upload process will continue only if the selected image did not already exist in an uploads folder.
  • 17. After that we check does a selected file of a user, contain any of this extension (JPG, JPEG, PNG, GIF, & PDF). If yes, we continue the upload process else we print an error message.
  • 19. If an image is successfully uploaded in uploads folder on the server then we store the image details by using code line 21 and 22.
  • This is how we upload image file into the server using PHP and MySQL Database.

You may also like this handpick tutorial for you.

Also, watch the video of this tutorial.

Share this post