Deleting a server file

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.";

<?php
  $file_to_delete = $_GET['file'];
  if (is_file($file_to_delete)){
    echo (unlink($file_to_delete) ? "File Deleted" : "Problem deleting file";

  }
?>

I'm not going to lie, don't know a better way to sanitize the $_GET['file'] other than check if it's a file. If this isn't a valid way, experts please chime in. (Maybe follow the guidelines present in this SO topic?)


Sometimes you may want to create the path dynamically.

For example, I am using a CMS in different places therefore I should not use fixed definitions.

My project structure:

-myProject
|-admin
|--app
|---controllers
|-upload

$base_directory = dirname(__FILE__);
echo $base_directory; //'/home/myProject/public_html/admin/app/controlers/'

This is taking the path to the running php file.

My php file in 'admin/app/controllers/'

But upload file in 'upload/'

We need to delete unnecessary directories for the correct path. The file in the upload folder so we dont need to 'admin/app/controllers/' is unnecessary. So we are removing this part.

$path = str_replace('admin/app/controllers/', '', $path);
echo $path;  //'/home/myProject/public_html/upload/myFile'

Now we have correct path and we can delete the file.

if (file_exists($path)){
    if(unlink($path)){
       echo "File deleted";
    }
}else{
     echo "File is not exists";
}