Single image upload and delete

To successfully upload an image to your databse and uploads folder you will first need to create two additional folders. One folder will be for the code to execute the form submission and more code to view and delete the images from the database and uploads folder. The second folder will be the uploads folder itself which the images will be saved to. The uploads folder requires specific permissions to allow users to upload and delete images from it.

Depending on you server type will determine what command you need to run in the terminal. As I am on a Linux Ubuntu server the command is
"chmod 757 public_html/uploads" If you can access your server through filezilla then you can also change the permissions that way too.

First step: create a simple html form to upload the image. As this is basic, I only have one input in the form. You may need to add more fields depending on how much data your looking to submit such as title, description etc.

                
                    <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data">
                        <div class="form-group">
                            <label>Image</label>
                            <input type="file" name="img" class="form-control">
                        </div>
                        <button name="submit" class="btn btn-primary btn-block">Add image</button>
                    </form>
                
            

Next: Check the image name does not already exsist in the database. If the name does not exsist then we can attempt to upload the image. During the upload we will do another check and this will be to make sure that only valid file types are submitted. We do not want malicious files or folders being inserted into the database and into our websites folder structure.

                
                if(isset($_POST['submit']))
                    {
                        $img = basename($_FILES['img']['name']);
                        //lets make sure the image does not already exist in the database
                        $sql = "SELECT img FROM images WHERE img = '$img'";
                        $statement = $db->prepare($sql);
                        $statement->execute();
                        $result = $statement->fetchAll();
                        $total_row = $statement->rowCount();

                        if($total_row > 0)
                            {
                                $exists = "<div class='alert alert-danger'>The image you are trying to upload already exists in the database. Please <a href='./'>try again</a>";
                            }
                        else   
                            {
                                //lets upload the image to the database and the uploads folder
                                $uploads_dir = '../uploads'; //we will change the permission for this folder to allow users to upload images and delete images
                                $tmp_name = $_FILES['img']['tmp_name'];
                                $img = basename($_FILES['img']['name']);
                                $fileType = strtolower(pathinfo($img, PATHINFO_EXTENSION));
                                $validFileType = array('JPG', 'PNG', 'JPEG', 'jpg', 'png', 'jpeg', 'gif');
                                if(in_array($fileType, $validFileType))
                                    {
                                        move_uploaded_file($tmp_name, "$uploads_dir/$img");
                                        $sql = "INSERT INTO images (img) VALUES (:img)";
                                        $statement = $db->prepare($sql);
                                        $statement->bindParam(':img'    ,   $img,   PDO::PARAM_STR);
                                        try 
                                            {
                                                $statement->execute();
                                                $success = "<div class='alert alert-success'>Upload successful - view images <a href='delete-images'>here</a></div>";
                                            }
                                        catch (PDOException $e)
                                            {
                                                echo $e;
                                                $failed = "<div class='alert alert-danger'>There was an issue, please try again</div>";
                                            }
                                    }
                                else
                                    {
                                        $error = "<div class='alert alert-danger'>Only png, jpg and gif files are allowed to be uploaded</div>";
                                    }
                            }
                        $db = null;
                    }
                
            

The third and final step is to view the images with the option to delete.

                
                if(isset($_POST['submit']))
                    {
                        $id = $_POST['id'];
                        $sql = "SELECT img FROM images WHERE id = '$id'";
                        $statement = $db->prepare($sql);
                        $statement->execute();
                        $result = $statement->fetchAll();
                        $img = "";
                        foreach($result as $row)
                            {
                                $img = $row['img'];
                            }

                        $sql = "DELETE FROM images WHERE id = :id ";
                        $statement = $db->prepare($sql);
                        $statement->bindParam(':id' , $id,  PDO::PARAM_INT);
                        try{
                            $statement->execute();
                            echo "<div class='col-12 col-md-6 mx-auto'>
                                    <div class='alert alert-success'>Image has been deleted. Upload more images <a href='./'>here</a>
                                    </div>
                                </div>";
                            $dir = "../uploads/".$img;
                            if(file_exists($dir))
                                {
                                    unlink($dir);
                                }
                        }
                        catch(PDOException $e)
                            {
                                echo $e;
                                echo "<div class='container' style='max-height: 50px; max-width: 250px;'><p class='alert-danger'>Delete failed. please try again</p></div>";
                            }
                    }

                    //view images with delete button

                    $sql = "SELECT * FROM images ORDER BY date DESC";
                    $statement = $db->prepare($sql);
                    $statement->execute();
                    $result = $statement->fetchAll();
                    foreach($result as $row)
                        {
                            echo "<div class='col-lg-3 col-md-4 col-6'>
                                    <form action='' method='post'>
                                    <img class='img-thumbnail' src='../uploads/".$row['img']."'>> 
                                    <input type='hidden' name='id' value='".$row["id"]."'>
                                    <button class='btn btn-danger' name='submit' style='margin-bottom: 5px;'>Delete ".$row['img']."</button>
                                    </form>
                                </div>";
                        }