简体   繁体   中英

Deleting a particular file in php

I am practicing uploading and deleting files in php and I've encountered a problem.

I have this code:

if($files)
{
    foreach($files as $file)
    {
        echo '<a href="files_storage/'.$file.'" download>'.$file.'</a><br>';
    }
}
else
{
    echo 'There are currently no files.';
}

It displays all files from a directory. I want to add a delete button for every file. Something like this:

在此处输入图片说明

Should I create different form for every file? If I do so, how would I identify which file to be deleted when a form is submitted? Any suggestions?

You could put all the submit buttons in one form and set the name attribute of every button to delete[' . $file . '] delete[' . $file . '] delete[' . $file . '] . Then, in the beginning of the loop, check if $_POST['delete'][$file] is set and delete it.

if(!empty($files)){
    echo '<form action="" method="post">';
    foreach($files as $file){
        if(isset($_POST['delete'][$file]) && file_exists($file)){
            unlink($file);
            continue;
        }
        echo '<a href="files_storage/'.$file.'" download>'.$file.'</a><input type="submit" name="delete[' . $file . ']" value="Delete this file" /><br>';
    }
    echo '</form>';
}
if(empty($files)){ //check again, since $files may be empty after deletion
    echo 'There are currently no files.';
}

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