从PHP目录中删除文件

时间:2015-02-23 15:27:33

标签: php directory unlink delete-file

我设法将文件上传并下载到目录中,但我无法在删除选项中找到任何内容。我已经编写了一些代码,但它只是起作用:这是我的文件上传:

<?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>';  
}


?>

这是我的显示和下载并删除:

<?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";

?>

这是我的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

?>

有谁知道如何修复它?

1 个答案:

答案 0 :(得分:0)

尝试更改:

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

对此:

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

删除时,您无法在files目录中工作。