Search code examples
phpdirectoryunlink

PHP - Deleting a file listed in a Directory through a hyperlink


I'm trying to list all files in a directory and delete a file if a 'DELETE' link is clicked, however, it's telling me that the file is non existant showing me these error messages:

Notice: Undefined index: dir in C:\xampp\htdocs\Task2PHP\final\deletefile.php on line 4

Warning: unlink(adam.png): No such file or directory in C:\xampp\htdocs\Task2PHP\final\deletefile.php on line 7

files.php (code block):

@$selected_path = $_POST['myFiles'];

$dir = $selected_path;

echo "<br>Current files in: " . $dir . " <br /><br />";

if ($handle = opendir($dir)) {
   while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {


            echo "$file <a href=deletefile.php?file=$file>DELETE</a><br />"; 
        }
    }
    closedir($handle);
}

deletefile.php

<?php
session_start();
$username = $_SESSION['username'];
$dir = $_SESSION['dir'];
$file= basename($_GET['file']);//added

unlink("$file");

?>

Solution

  • The unlink() function will look for adam.png relative to the location of deletefile.php. If the image is inside a directory, you'll need to something like this:

    session_start();
    $username = $_SESSION['username'];
    $dir = $_SESSION['dir'];
    $file= basename($_GET['file']);//added
    unlink('folder/container/'.$file); // or maybe you want unlink($dir.$file);
    

    Alternatively, you could pass the directory to deletefile.php by changing the echo statement in your files.php to:

    echo "$file <a href=\"deletefile.php?file=$file&dir=$dir\">DELETE</a><br />"; 
    

    You can then access this inside of deletefile.php through $_GET['dir'], so your code would be something like:

    $dir = $_GET['dir'];
    $file = basename($_GET['file']);
    unlink($dir.$file);