我正在尝试使用PHP从目录中删除给定文件。这是我试过的代码:
// Get the file name
$id = '61514';
// Get the folder path
$uploads_folder_dir = 'some/dir';
// Check if the directory exists
if ( ! file_exists( $uploads_folder_dir ) )
return false;
// Open the directory
if ( $dir = opendir( $uploads_folder_dir ) ) {
// Loop through each file in the directory
while ( false !== ( $file = readdir( $dir ) ) ) {
// Target the file to be deleted and delete. All files in folder are .png
if ( $file == ( $id . '.png' ) )
@unlink( $uploads_folder_dir . '/' . $file );
}
}
// Housekeeping
closedir( $dir );
@rmdir( $uploads_folder_dir );
每次运行代码时,我尝试删除的特定文件都不会被删除。
我的猜测是当我循环遍历目录时,找到该文件的逻辑无法正常工作。我可以确认文件61514.png
肯定在目录some/dir
希望有人能在这里发现我出错的地方?
答案 0 :(得分:0)
为什么要循环浏览文件?这个会容易得多:
// Get the file name
$id = '61514';
// Get the folder path
$uploads_folder_dir = 'some/dir';
// Check if the directory exists
if ( ! file_exists( $uploads_folder_dir ) )
return false;
unlink("$uploads_folder_dir/$id.png");
// Housekeeping
@rmdir( $uploads_folder_dir );
答案 1 :(得分:0)
首先通过打印整个文件路径(如
)调试文件路径是否正常// Target the file to be deleted and delete. All files in folder are .png
if ( $file == ( $id . '.png' ) ){
echo $uploads_folder_dir . '/' . $file; die;
@unlink( $uploads_folder_dir . '/' . $file );
}
}
答案 2 :(得分:0)
@unlink - >使用unlink如果你没有看到权限被拒绝的问题,那么文件和" dir"应该删除。