简体   繁体   中英

Delete file from directory PHP

I have managed to get my file upload and download to a directory working, I just can't find anything on the delete option. I've written some code but it just dosn't work: this is my file upload:

<?php
if(isset($_FILES['file'])){
    $file = $_FILES['file'];
        //file properties

        $file_name = $file['name'];
        $file_tmp = $file['tmp_name'];
        $file_size = $file['size'];
        $file_error = $file['error'];
        //the file extension
        $file_ext = explode ('.', $file_name);
        $file_ext = strtolower(end($file_ext));
        //allowed extensions
        $allowed = array('txt', 'jpg');

        if(in_array($file_ext, $allowed)){
            if($file_error === 0){
                //allowed size
                if($file_size<= 2097152){
                    $file_name_new = $file_name;
                    $file_destination = 'files/' . $file_name_new;

                    if(move_uploaded_file($file_tmp, $file_destination)){
                        echo '<div class="errors"> Uploaded Succesfully </div>';

                    }

                }


            }
        }else echo ' <div class="errors"> Wrong file type </div>';  
}


?>

This is my display and download and delete:

<?php
$dir = "files/";
if ($opendir = opendir($dir)){
    while ($fileopen = readdir($opendir)){
        if ($fileopen != "." && $fileopen != ".." )
        echo "<a href='$dir$fileopen' download>$fileopen</br>";
        echo "<a href='deletefile.php?file=".$fileopen."'>DELETE";
    }

}
    else "could not open folder";

?>

and this is my deletefile.php :

$filename = $_GET['$fileopen']; //get the filename
unlink('final/files'.DIRECTORY_SEPARATOR.$filename); //delete it
header('location: upload.php'); //redirect back to the other page

?>

anyone knows how to fix it?

Try changing:

     unlink('final/files'.DIRECTORY_SEPARATOR.$filename);

To this:

     unlink('files'.DIRECTORY_SEPARATOR.$filename);

You aren't working in the files directory when you are deleting.

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