PHP unlink function help
I wrote a PHP script to delete files selected in a gridview. This is the first time I've done this. The script works fine on my local development machine but I don't know if this is the proper way to do it. I'd like to find out what possible problems can I run into when deleting files and how can I modify this to prevent problems.
I was looking at this page to get the basic idea: 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_er开发者_如何学Pythonror);
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;
}
?>
Thank you!
Edit: Would it be better this way?
$fh = fopen($file_to_delete, 'w') or die($failed_to_open_file);
fclose($fh);
unlink($file_to_delete);
Not all files can be unlinked because of permissions, so check the return value of that call.
精彩评论