Deleting a server file

user606263 picture user606263 · Feb 10, 2011 · Viewed 48.1k times · Source

I'm looking for a way to delete a file from the server using PHP. Basically I have my files listed on a page in this manner:

<ul>
    <li><a href="delete_file.php?file=uploads/file_01.jpg">Delete File 01</a></li>
    <li><a href="delete_file.php?file=uploads/file_02.jpg">Delete File 02</a></li>
    <li><a href="delete_file.php?file=uploads/file_03.jpg">Delete File 03</a></li>
</ul>

The problem is I'm not sure how to get my delete_file.php file to work. I believe it needs to be something like this:

<?php 
    $path="uploads/file_01.jpg";
    if(unlink($path)) echo "File Deleted"; 
?>

...but I'm not sure how to get the $path to change to the file I had clicked on to delete.

Answer

Patrick picture Patrick · Feb 10, 2011

while you have to be incredibly careful with giving a user the ability to delete files, I'll give you enough rope to hang yourself

define a base directory that will contain any files that will be deleted

$base_directory = '/home/myuser/';

Then delete the file

if(unlink($base_directory.$_GET['file']))
    echo "File Deleted.";