PHP取消链接功能帮助

时间:2011-06-18 22:25:00

标签: php unlink

我编写了一个PHP脚本来删除在gridview中选择的文件。这是我第一次这样做。该脚本在我的本地开发机器上工作正常,但我不知道这是否是正确的方法。我想了解删除文件时可能遇到的问题,如何修改此问题以防止出现问题。

我正在查看此页面以获得基本想法:http://www.php.net/manual/en/function.unlink.php

<?php
// get required includes
require_once(ROOT_PATH.'user/controls/snippets/error_messages.php');
require_once(ROOT_PATH.'user/controls/accordion/get_user_name.php');

// ------------------------------------------------------------
// DELETE SELECTED FILES
// ------------------------------------------------------------
if(isset($_POST['delete_file']) && isset($_POST['checked2']))
{
    $checked = array_map('intval',$_POST['checked2']);
    $delete_list = implode(", ", $checked);

    // DB: get file names to delete
    $get_file_names = mysqli_query($conn, "SELECT FileName FROM downloads WHERE DownloadId IN ($delete_list) AND UserName = '$user_name'")
    or die($dataaccess_error);

    // delete files from server
    while($row = mysqli_fetch_array($get_file_names))
    {
        $dir = DOWNLOAD_DIRECTORY;
        $file_name = $row['FileName'];
        $file_to_delete = $dir.$file_name;
        unlink($file_to_delete);
    }

    // DB: delete selected file references from db
    $delete_selected = mysqli_query($conn, "DELETE FROM downloads WHERE DownloadId IN ($delete_list) AND UserName = '$user_name'")
    or die($dataaccess_error);

    if(mysqli_affected_rows($conn) > 0)
    {
        $effected_rows = mysqli_affected_rows($conn);
        echo "<div class='msgBox2b noBorder'>SUCCESS: ($effected_rows) FILE(S) have been DELETED..</div>";
    }
}
elseif(isset($_POST['delete_file']) && !isset($_POST['checked2']))
{
    echo $msg_error;
}
?>

谢谢!

编辑:这样会更好吗?

$fh = fopen($file_to_delete, 'w') or die($failed_to_open_file);
fclose($fh);
unlink($file_to_delete);

1 个答案:

答案 0 :(得分:1)

由于权限,并非所有文件都可以取消链接,因此请检查该调用的返回值。