Delete Image from Folder

Asked

Viewed 480 times

0

I have this PHP code that returns me all the images inside the folder:

 <?php $files = glob("*.*"); for ($i=1; $i<count($files); $i++) { $num = $files[$i]; echo '<img src="'.$num.'" alt="ran
dom image">'."&nbsp;&nbsp;"; } ?>

However, there would be some way to put a delete button on each of the photos that appear?

1 answer

0


Just you add one anchor with a parameter and then check if the parameter was passed, if it was, you use the function unlink to remove.

Example:

<?php

/* Verifica se o parâmetro `remove` foi passado na URL */
if (isset($_GET["remove"])) {

    /* Caso tenha sido passado, decodifica o parâmetro e remove o arquivo */
    unlink(base64_decode($_GET["remove"]));
}

$files = glob("*.*");

for ($i=0; $i<count($files); $i++) {
    $num = $files[$i];

    /**
     * Exibe a imagem com um `<a></a>`
     * No atributo `href`, basta utilizarmos o parâmetro `remove`
     * com o valor codificado em base64, isso evitará problemas
     * com caracteres especiais
     */
    echo '<img src="'.$num.'" alt="random image" /><a href="?remove='.base64_encode($num).'">Remover</a><br>';
}

?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.