【问题标题】:How to delete files in a directory with PHP on a file hosting site?如何在文件托管站点上使用 PHP 删除目录中的文件?
【发布时间】:2014-01-07 12:57:57
【问题描述】:

我正在尝试为我的家人、几个朋友和我使用一个简单的文件托管网站。我有整个系统设置,除了一件事......我找不到让用户删除文件而无需访问 FTP 的方法。我将在下面将用于列出文件的代码发布给用户。我希望为用户上传的每个新文件自动生成一个删除按钮。

列出文件的代码:

$directory = 'uploads/' . $_SESSION['user'] . '/';
if ($handle = opendir($directory)) {
    echo '<h3>Your files are listed below</h3>';    
    while ($file = readdir($handle)) {
        if ($file != '.' && $file != '..') {
            echo '<a target="_blank" href="' . $directory . '/' . $file . '">' . $file . '<br>';    
        }
    }
}

【问题讨论】:

    标签: javascript php html xhtml directory


    【解决方案1】:

    可以使用unlink()php函数

    参考:http://www.php.net/unlink

    <?php
       $mask = "*.jpg"
      array_map( "unlink", glob( $mask ) );
    ?>
    

    【讨论】:

    • 我试过了,但它没有链接到任何文件,因为我用while循环列出文件
    • 确保您拥有删除文件的必要权限
    • 我拥有所有权限,只是它不知道文件类型或有关文件的任何信息。请记住,用户可以上传他们想要的任何文件。
    • 除了确切的路径和名称之外,它不需要知道任何关于文件类型的信息。
    • 如果您有权限,那么unlink 将起作用。如果没有,那么其他事情就是错误的
    【解决方案2】:
    $directory = 'uploads/' . $_SESSION['user'] . '/';
    
    if(isset($_REQUEST['DelFile'])) {
        $DeleteFile = $_REQUEST['DelFile'];
        if(file_exists($directory.$DeleteFile)) {
            @unlink($directory.$DeleteFile);
            header("location:SamePageURL.php?msg=1");
        } else header("location:SamePageURL.php?msg=2");
    }
    
    if ($handle = opendir($directory)) {
    echo '<h3>Your files are listed below</h3>';    
        while ($file = readdir($handle)) {
            if ($file != '.' && $file != '..') {
                echo '<a target="_blank" href="'.$directory.'/'.$file.'">' . $file.' <a href="SamePageURL.php?DelFile='.$file.'">Delete</a> <br>';  
            }
        }
    }
    
    if(isset($_REQUEST['msg'])) {
        $Message = $_REQUEST['msg'];
        if($Message == 1) echo "File deleted sucessfully";
        else if($Message == 1) echo "File not found";
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 2011-01-04
    • 2021-06-08
    • 1970-01-01
    相关资源
    最近更新 更多