-1

Why won't the image from directory get deleted?

The rest working fine but just the image is not getting unlinked.

Here is my php code:

if(isset($_POST['delbtn'])){
$code = $_POST['delete'];

$stmt = $db->prepare("SELECT * FROM interviews WHERE reference = :reference");
$stmt->bindParam(':reference', $code, PDO::PARAM_STR);
$stmt->execute();
$cnt = $stmt->rowCount();
if($cnt!='0'){

$query = "delete from interviews where id IN(".$_GET['coach'].")";
$stmt = $db->prepare($query);
$stmt->execute();
while($rw = $stmt->fetch())
 {
     $file='uploads/interviews/'.$rw['image'];
     @unlink($file);
 }          
                echo "<script type='text/javascript'>
                alert('Entry successfully deleted.');
                window.location.href = 'need-help-with-interview.php';
                </script>";
exit;
}else{
                echo "<script type='text/javascript'>
                alert('You are not authorized to delete this entry.');
                window.location.href = 'need-help-with-interview.php';
                </script>";
exit;
 }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
  • 1
    You are suppressing the error message using `@` (at `@unlink($file);`). Suppressing errors is usually not recommended. You should take a look at the error log of your webserver, it should give you more information. Also, your `DELETE` query is susceptible to [SQL Injection Attacks](https://stackoverflow.com/questions/332365/how-does-the-sql-injection-from-the-bobby-tables-xkcd-comic-work). – Minding Mar 26 '20 at 15:54

1 Answers1

0
$query = "delete from interviews where id IN(".$_GET['coach'].")";
$stmt = $db->prepare($query);
$stmt->execute();
while($rw = $stmt->fetch())
{
 $file='uploads/interviews/'.$rw['image'];
 @unlink($file);
} 

You are writing code to delete from table which will return Boolean value not rows. First select data which you are deleting from database and then delete images from folder.

After deleting images delete records from DB.

(Note: you have a SQL injection security vulnerability in your delete query. This could be easily modified by an attacker to delete everything in your table. Please use parameter binding to fix this).

halfer
  • 19,824
  • 17
  • 99
  • 186
Deepak
  • 548
  • 3
  • 15
  • 1
    Answers that replicate SQL injection vulnerabilities should at least make note of them, so that the question author is in no doubt they have a serious problem to fix. – halfer Mar 30 '20 at 09:39