post icon

Deleting a file in php using unlink

Tonight I was having troubles deleting a file from a directory in an application I am working on. It kept deleting the entry in the table but not the actual file from the directory. Here is what the code looked like:

< ?php
$sql = "DELETE FROM uploads WHERE upload_id = $id";
$result = mysql_query($sql);
//if it ran ok
if (mysql_affected_rows() == 1) {
 delete the file from the uploads dir
 unlink('uploads/'$row['file_name']);
}
?>

I couldn’t figure out for the life of me then I tried this:

< ?php
//delete the file from the uploads dir
unlink('uploads/' . $row['file_name']);
$sql = "DELETE FROM uploads WHERE upload_id = $id";
$result = mysql_query($sql);
//if it ran ok
if (mysql_affected_rows() == 1) {
 //do something
}
?>

It worked perfect! I just had to seperate the name ($row['file_name']), which could also be a variable with a space: ‘uploads/’ . I also had to make sure the unlink was before the DELETE query because if it was after the query it would be trying to delete something that wasn’t there.

31. Mar, 2007

2 Comments

Leave a comment
  1. Shaun
    21. Aug, 2007 at 9:08 am #

    Bout time someone published the solution, lord knows php.net’s manual and convoluted examples are of no help!!! Thanks for posting this!

  2. Darren
    21. Aug, 2007 at 6:27 pm #

    Thanks Shaun for the positive feedback! It’s good to know someone gets some help from my posts.