-1

I'm trying to learn PHP, but I got stuck with this issue. The unlink() function is not deleting the old file. It's supposed to delete the file based on the Youtube tutorial I've seen. My goal is to delete the old image when a new image has been loaded, but I can't find the issue behind my code. Can anyone help me? Any response will be appreciated.

edit-category.php

<?php 
include('includes/header.php');
include('../middleware/adminMiddleware.php');


?>

<!-- Add cards for better UI -->

<div class="container">
    <div class="row">
        <div class="col-md-12"> 
            <?php if(isset($_GET['id'])) { 

                $id = $_GET['id'];  
                $category = getByID("categories", $id);

                if(mysqli_num_rows($category) > 0)

                {

                    # '$data' will store each columns from the category table

                    $data = mysqli_fetch_array($category);


            ?>

                    <div class="card">
                        <div class="card-header">
                            <h4>Edit Category </h4>
                        </div>
                        <div class="card-body">
                            <form action="code.php" method="POST" enctype="multipart/form-data">
                                <div class="row">

                                    <div class="col-md-6">

                                        <label for="">Name</label>

                                        <input type="hidden" name="category_id" value="<?= $data['id'] ?>" class="form-control" placeholder="Enter Category Name" >

                                        <!-- Store database records to the value parameter -->

                                        <input type="text" name="name" value="<?= $data['name'] ?>" class="form-control" placeholder="Enter Category Name" >


                                    </div>
                                    <div class="col-md-6">
                                        <label for="">Slug</label>
                                        <input type="text" name="slug" value="<?= $data['slug'] ?>" class="form-control" placeholder="Enter Slug">
                                    </div>
                                    <div class="col-md-12">
                                        <label for="">Description</label>
                                        <textarea rows="3" name="description" class="form-control" placeholder="Enter Description"> <?= $data['description'] ?></textarea>
                                    </div>


                                    <div class="col-md-12">

                                        <label for="">Upload Image</label>
                                        <input type="file" name="image" class="form-control">


                                        <label for="">Current Image</label>
                                        <input type="hidden" name="old_image" value="<?= $data['image'] ?>">
                                        <img src="../uploads/<?= $data['image'] ?>" alt="" height="100px" width="100px">


                                    </div>


                                    <div class="col-md-12">
                                        <label for="">Meta Title</label>
                                        <input type="text" name="meta_title" value="<?= $data['meta_title'] ?>" class="form-control" placeholder="Enter Title">
                                    </div>
                                    <div class="col-md-12">
                                        <label for="">Meta Description</label>
                                        <textarea rows="3" name="meta_description" class="form-control" placeholder="Enter Meta Description"><?= $data['meta_description'] ?></textarea>
                                    </div>
                                    <div class="col-md-12">
                                        <label for="">Meta Keywords</label>
                                        <textarea rows="3" name="meta_keywords" class="form-control" placeholder="Enter Keywords"><?= $data['meta_keywords'] ?></textarea>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="">Status</label>
                                        <input type="checkbox" <?= $data['status'] ? "checked":"" ?>name="status">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="">Popular</label>
                                        <input type="checkbox" <?= $data['popular'] ? "checked":"" ?> name="popular">
                                    </div>
                                    <div class="col-md-12">
                                        <button type="submit" class="btn btn-primary" name="update_category_btn">
                                            Update
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>          
                    </div>

            <!-- Opened a closing statement here for the if/else -->

            <?php

                }
            

            else 
            {
                echo "Category not found";
            }


            ?>

            

            <?php } else { echo "Something went wrong"; } ?>
        </div>  
    </div>
</div>
<?php include('includes/footer.php')?>

code.php

else if(isset($_POST['update_category_btn']))
{
    $category_id = $_POST['category_id']; 
    $name = $_POST['name'];
    $slug = $_POST['slug'];
    $description = $_POST['description'];
    $meta_title = $_POST['meta_title'];
    $meta_description = $_POST['meta_description'];
    $meta_keywords = $_POST['meta_keywords'];
    $status = isset($_POST['status']) ? '1':'0' ;
    $popular = isset($_POST['popular']) ? '1':'0' ;

    // Use this variable for uploading new image 
    $new_image = $_FILES['image']['name'];

    // Store old image here
    $old_image = $_POST['old_image'];

    // If new image field is not empty, update image 
    if($new_image != "")
    {
        // $update_filename = $new_image;
        $image_ext = pathinfo($new_image, PATHINFO_EXTENSION);
        $update_filename = time().'.'.$image_ext;
    }

    // If it is empty, use old image     
    else
    {
        $update_filename = $old_image;
    }

    $path = "../uploads";

    $update_query = "UPDATE categories SET name='$name', slug='$slug', description='$description', meta_title='$meta_title', meta_description='$meta_description', meta_keywords='$meta_keywords', status='$status', popular='$popular', image='$update_filename' WHERE id= '$category_id' ";

    $update_query_run = mysqli_query($con, $update_query);

    if($update_query_run)
    {
        if($_FILES['image']['name'] != "")
        {
            move_uploaded_file($_FILES['image']['tmp_name'], $path.'/'.$update_filename);

            if(file_exists("../uploads/".$old_image))
            {
                unlink("../uploads".$old_image);
            }

        }
        redirect("edit-category.php?id=$category_id", "Category updated successfully!");
    }

    else 
    {
        redirect("edit-category.php?id=$category_id", "Update failed");     
    }
}

  • Have you checked if it goes inside file_exists("../uploads/".$old_image) condition? – Monish Khatri Jun 30 '22 at 06:39
  • 1
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman Jun 30 '22 at 07:44

1 Answers1

0

Look like you miss forward slash while doing unlink

change

if(file_exists("../uploads/".$old_image))
{
     unlink("../uploads".$old_image);
}

to

if(file_exists("../uploads/".$old_image))
{
     unlink("../uploads/".$old_image);
}
B. Desai
  • 16,414
  • 5
  • 26
  • 47