Delete file and record

Go To StackoverFlow.com

-2

I have the following code which deletes a record from a database. However I would like it also to remove an associated file from the server. One of the columns contains the path to the file. Can someone explain how I would use the unlink function here?

<?php

 include('config.php');

 if (isset($_GET['id']) && is_numeric($_GET['id']))
 {    
     $id = $_GET['id'];      
     $result = mysql_query("DELETE FROM images WHERE id=$id")     
     or die(mysql_error());      
     header("Location: view.php");
 }   
 else    
 {
     header("Location: view.php");
 }

?>
2012-04-04 21:59
by Owen Walsh
select the info you need from the table before you delete - David Chan 2012-04-04 22:02


2

Before anything else, fix your SQL injection holes.

To answer your question, first you have to select the record to details about that local file. Once you've nuked the database record, you've lost the only place where the location of the file is stored, so get that data first.

That's make it, in pseudo-code:

  1. fetch file location
  2. delete file
  3. delete database record
2012-04-04 22:03
by Marc B
is_numeric() doesn't take care of all cases - PeeHaa 2012-04-04 22:03
it'd prevent the query from running in the first place, but still, if that if() ever gets changed, the rest of the code is an injection attack waiting to happen - Marc B 2012-04-04 22:04


1

You can just do a query first to retrieve the imagename and after that simply delete the file:

unlink($theFilenameRetrievedFromDb);
2012-04-04 22:02
by PeeHaa


1

You have to first make a select statement to your database to know the path of your file. Once this is done, you can use unlink on this path, then make your delete statement.

2012-04-04 22:03
by Kiryaka
Ads