简体   繁体   中英

Deleting specific files in PHP

So I've created a small administration panel with php that will upload files into a directory that will be shown on the main page. Now the thing is, how do I delete a file? I've already seen that people are using Ajax and jQuery to do this but I don't understand how to do this with a button.

This is my function that generates the image and the delete button, but when someone click on the button it should delete the associated image, I don't get it how to pass the image path or something :

$dirname = "img_show/";
$images = glob($dirname."*.{jpg,gif,png}",GLOB_BRACE);

foreach($images as $image) {
     echo '<img src="'.$image.'" width="25%" /><br/>';
     echo '<form method="post">
            <input type="submit" name="delete" value="Effacer" />
            </form>';
 }

It looks like you are trying to delete files that are retrieved from the "img_show" directory and not storing it in the database.

The easiest way to delete the selected file is to update your code with the following,

// Delete an image if the delete button was clicked
if(isset($_POST['delete']) && $_POST['delete'] == 'Effacer') {
    unlink($_POST['file']);
}


// Print the available list of images in the directory
$dirname = "img_show/";
$images = glob($dirname."*.{jpg,gif,png}",GLOB_BRACE);

foreach($images as $image) {
    echo '<img src="'.$image.'" width="25%" /><br/>';
    echo '<form method="post">
    <input type="hidden" name="file" value="'. $image .'" />
    <input type="submit" name="delete" value="Effacer" />
    </form>';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM