0

I have a bunch of files that I show on the page from folder, and every file has a button to delete it from the folder, I'm using hidden input to get the file name and to link it with path to delete it. This hidden input changes with each file I want to delete. How can I get the first item of $_POST array to link it with path to delete the file? This is my code:

<form action="deleteFile.php" method="POST">
      <input type="hidden" name="<?php echo $file ?>">
      <button type="submit" name="deleteFile" class="delete"><i class="far fa-trash-alt"></i></button>
</form>

and this is the deleteFile.php:

$curret_path = $_SESSION['folder_path'];
if (isset($_POST['deleteFile'])) {
    $fileName = $_POST[0];
    unlink($curret_path . '/' . $fileName);
}

finally, this image attached show my projectenter image description here

  • deleting files like this could be dangerous – suresh bambhaniya Mar 28 '21 at 19:06
  • It would perhaps be easier to use a fixed `name` attribute on the hidden input and pass the file/path as the `value`. [hidden input](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/hidden). Alternatively in php [array_shift](https://www.php.net/manual/en/function.array-shift.php) or some other array functions can be used. – Remy Mar 28 '21 at 19:06

1 Answers1

2

I would make the following changes to your form making the assumption that $file is set somewhere before the form correctly. Not shown in the original posting by OP.

<form action="deleteFile.php" method="POST">
      <input type="hidden" name="file_name" value="<?php echo $file ?>">
      <button type="submit" name="deleteFile" class="delete"><i class="far fa-trash-alt"></i></button>
</form>
<?php
$current_path = $_SESSION['folder_path'];
if ($_POST['file_name']) {
    $fileName = $_POST['file_name'];
    if (file_exists(sprintf('%s/%s', $current_path, $fileName))) {
        unlink(sprintf("%s/%s", $current_path, $fileName));
    }
}

The PHP changes include checking to make sure the file exists first before it tries to delete it.

CAUTION

This is a VERY dangerous thing to put into production. There's no checks on the file_name which could be changed in the form to ../../../etc/pwd or something similar. For further information here's a detailed explanation: How to delete a file via PHP?

hppycoder
  • 1,016
  • 1
  • 6
  • 13
  • Thank you so much, but it's not production, it's just for learning php! But I have a question here: What if the file name is directory Not a file? – Abdallah M Yassin Mar 28 '21 at 19:18
  • You could use `is_dir()` combined with `rmdir()` to remove the directory. Glad to hear it's not in production. – hppycoder Mar 28 '21 at 19:23