1

I have the following code:

<?php

include "../../koneksi.php";

$module=$_GET['module'];
$act=$_GET['act'];
$Gfile_id=$_GET['file_id'];

if ($module=='galleryPhoto' AND $act=='delete'){
    $del=mysql_query("DELETE FROM gallery_photo WHERE file_id='$Gfile_id'");
    header("location:../?v=gallery_foto&info=Success");
}

?>

I can delete the database row, but not my images in directory. How can I delete the images from the directory?

Kevin
  • 41,694
  • 12
  • 53
  • 70

2 Answers2

1

You can use unlink() function

unlink()

1

If you want to delete the file, of course it won't be deleted using those functions, you need to use unlink():

unlink('path/to/the/file.png');

Obligatory Note:

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

First, (and I hope) you need to have saved the filename of that file that you want to be deleted.

Then before deleting the row, you could get that filename first. Then just add/concatenate it in the path that the unlink() will be using:

<?php

// connection
$con = new mysqli('localhost', 'username', 'password', 'database_name');

if(isset($_GET['module'], $_GET['act'], $_GET['file_id'])) {
    $module = $_GET['module'];
    $act = $_GET['act'];
    $Gfile_id = $_GET['file_id'];

    if($module == 'galleryPhoto' && $act == 'delete') {

        // get the file path first that is saved
        $sql = 'SELECT file_path FROM gallery_photo WHERE file_id = ?';
        $select = $con->prepare($sql);
        $select->bind_param('s', $Gfile_id);
        $select->execute();
        $select->bind_result($file_path);
        $select->fetch(); // fetch single row

        // delete the file
        unlink('path/to/images/' . $file_path);

        // then delete that row
        $sql = 'DELETE FROM gallery_photo WHERE file_id = ?';
        $delete = $con->prepare($sql);
        $delete->bind_param('s', $Gfile_id);
        $delete->execute();


        header('Location: ../?v=gallery_foto&info=Success');
    }
}

?>
Community
  • 1
  • 1
Kevin
  • 41,694
  • 12
  • 53
  • 70