In one PHP page I collect some data on the server (i.e. a list of the file in a folder) and show it into a table. The user may require to delete one file. Because I'm new to PHP I don't know if my approach is correct. Let's see some code:
list.php
<?php
$path = "/path/to/directory/";
$files = array_diff(scandir($path), array('.', '..'));
?>
<?php for ($i = 0; $i < count($files); $i++) { ?>
<tr>
<td class="d-none"><?php echo "{$i}"?></td>
<td><?php echo "{$files[$i]}"?></td>
<td>
<button type="button" class="btn btn-danger btn-sm delete"><i class="fas fa-trash-alt"></i></button>
</td>
</tr>
<?php } ?>
index.js
$(document).on("click", ".delete", function(e) {
var id = $(this).closest("tr").find('td').eq(0).html();
var filename = $(this).closest("tr").find('td').eq(1).html();
$.ajax({
url: "delete.php?id=" + id,
type: 'DELETE',
success: function(result) {
alert(result);
}
});
});
delete.php
$url = $_SERVER["REQUEST_URI"];
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $params);
$id = $params["id"];
$path = "/path/to/directory/";
//$filename = ???;
//unlink($path . $filename);
echo "success";
Some options I thought:
- Instead of the
idpass thefilenameas parameter of theDELETEquery. I guess it's not a good way. - list.php should place the file names into a db, so I can access them everywhere. Actually I did it, on a "live" db in
/dev/shmbut I wonder if it's a valid approach. Every time the page reloads I need to drop the table and create it again (on the page there's a refresh button for this purpose) - use the
$_SESSIONvariable to store the array so thedelete.phppage can retrieve thefilenameby itsid.
Please note, I'm not asking for an opinion about the three options. I'm asking what is the right approach from a technical point of view: safety, performances, reliability, etc...