Upload Images to Server PHP Tutorial (2022)

Upload Images to Server PHP Tutorial (2022)

Today we are going to learn on how to Upload Images to Server PHP Tutorial (2022). Server-side uploading make its easier using PHP.

There are lot of way to upload an images to server and display it to webpage. The image is upload in the server and the file name is store in the database. Later on its retrieve the filename from the database and display the image in the webpage.

Step on Upload Images to Server PHP Tutorial (2022)

  • Step 1: File’s Structure
  • Step 2: Creating Database and Table
  • Step 3: Configuration Database (dbConfig.php)
  • Step 4: Creating Uploading Form & Display Image (index.php)
  • Step 5: Creating Upload Script (upload.php)
  • Step 6: Testing
  • Step 7: Conclusion

Also Read: Laravel Load More Data on Scroll with jQuery and Ajax

File’s Structure

Before, Starting the tutorial first know the File’s Structure of the project.

File's Structure
File’s Structure

Creating Database and Table

Now, We are going to create a database and table. To create a database open phpmyadmin and create a new database with name “upload-images-php“. You can name its anything you like.

Create database
Create database

Now its time to create a images table. To create a images table run the query in SQL.

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,
 `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

This will create a images table with following fields – id, file_name, uploaded_on and status.

Images Table Fields
Images Table Fields

Configuration Database (dbConfig.php)

Now, Its time to connect or database with our project so create a file dbConfig.php and enter the following code into it.

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

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

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

Change the database details as per your information.

Also Read: Create Custom Helper in CodeIgniter (2022)

Creating Uploading Form & Display Image (index.php)

We are going to create a index.php for form and displaying uploaded images. First create a index.php in root of the directory and enter the following code.

Please note we had added bootstrap and jquery CDN.

<?php
    include_once 'upload.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>How to Upload Images to Server and Database (2022) - LaravelTuts</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="row mt-5">
            <div class="col-12">
                <form action="" method="post" enctype="multipart/form-data">
                    <div class="text-center justify-content-center align-items-center p-4 p-sm-5 border border-2 border-dashed position-relative rounded-3">
                        <img src="assets/gallery.svg" width="50px" height="50px" alt="">
                        <div>
                            <h6 class="my-2">Select Image File to Upload, or <a href="#!" class="text-primary">Browse</a></h6>
                            
                            <label style="cursor:pointer;">
                                <span> 
                                    <input class="form-control stretched-link" type="file" name="file" id="image" accept="image/gif, image/jpeg, image/png">
                                </span>
                            </label>
                            <p class="small mb-0 mt-2"><b>Note:</b> Only JPG, JPEG, PNG & GIF files are allowed to upload</p>
                        </div>
                    </div>
                    <div class="d-sm-flex justify-content-end mt-2">
                        <input type="submit" name="submit" value="Upload" class="btn btn-sm btn-primary mb-3">
                    </div>
                </form>
            </div>
        </div>
        <div class="row">
            <?php
                if(!empty($statusMsg)){
                    ?>
                        <div class="alert alert-secondary" role="alert">
                        <?php echo $statusMsg ?>
                        </div>
                    <?php
                }
            ?>
        </div>
        <div class="row g-2">
            <?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"];
                ?>
                    <div class="col-sm-6 col-lg-4 col-xl-3">
                        <div class="card shadow h-100">
                            <img src="<?php echo $imageURL; ?>" alt="" width="100%" class="card-img"/>
                        </div>
                    </div>
                <?php }
                }else{ ?>
                    <p>No image(s) found...</p>
                <?php 
                }
            ?>
        </div>
    </div>
</body>
</html>

Also Read: Integration PayPal Payment Gateway in PHP

There is a icon assets/gallery.svg for our form design.

Image Uploading Form - Upload Images to Server PHP Tutorial (2022)
Image Uploading Form
Displaying Uploaded images from database and error messages - Upload Images to Server PHP Tutorial (2022)
Displaying Uploaded images from database and error messages

Creating Upload Script (upload.php)

Its time to create a upload script to upload the image to server. Create a upload.php in root of the directory and enter the following code into it.

<?php
// Include the database configuration file
include 'dbConfig.php';
$statusMsg = '';

// File upload path
$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','pdf');
        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.";
                }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.';
    }
}

?> 

This will upload the image to server and add the image details to database. If there is error its will return a error message to main page. Please create uploads folder in root of the directory to store the images.

Testing

Now, Everything is good to go. You can test the project.

Testing - Upload Images to Server PHP Tutorial (2022)
Testing – How to Upload Images to Server and Database (2022)

Conclusion

We had learn Upload Images to Server PHP Tutorial (2022). Hope this tutorial helped you with learning PHP. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Also Read: Drag & Drop Reorder Images in PHP (2022)

I am Nitin Pujari, a full-stack developer and . I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, Php, Codeigniter, React, Angular, Vue, and Laravel.