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");
?>
The
unlink()function will look foradam.pngrelative to the location ofdeletefile.php. If the image is inside a directory, you’ll need to something like this:Alternatively, you could pass the directory to
deletefile.phpby changing theechostatement in yourfiles.phpto:You can then access this inside of
deletefile.phpthrough$_GET['dir'], so your code would be something like: