开发者

Deleting a server file

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.


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";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜