doujia1939
2015-02-18 13:02
浏览 6
已采纳

如何使用PHP删除目录中的文件?

I'm trying to delete a given file from a directory using PHP. Here is the code I've tried:

// 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 );

Each time I run the code, the particular file I'm trying to delete is not deleted.

My guess is when I'm looping through the directory, my logic to find the file isn't working. I can confirm that file 61514.png is definitely in directory some/dir

Hoping someone can spot where I'm going wrong here?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试使用PHP从目录中删除给定文件。 这是我尝试过的代码:

  //获取文件名
 $ id ='61514'; 
 
 //获取文件夹路径
  $ uploads_folder_dir ='some / dir'; 
 
 //检查目录是否存在
if(!file_exists($ uploads_folder_dir))
返回false; 
 
 //打开目录
if($ dir =  opendir($ uploads_folder_dir)){
 
 //循环遍历目录中的每个文件
而(false!==($ file = readdir($ dir))){
 
 //将文件定位到 被删除和删除。 文件夹中的所有文件都是.png 
 if($ file ==($ id。'。png'))
 @unlink($ uploads_folder_dir。'/'。$ file); 
} 
} 
 /  / housekeeping 
closedir($ dir); 
 @ rmdir($ uploads_folder_dir); 
   
 
 

每次运行代码时,我正在尝试的特定文件 删除不会被删除。

我的猜测是当我循环浏览目录时,找到该文件的逻辑无法正常工作。 我可以确认文件 61514.png 肯定在目录 some / dir

希望有人能发现我哪里出错了 在这里?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dty97501 2015-02-18 13:10
    已采纳

    First debug your file path is ok or not just by printing whole file path like

    // 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 );
            }
        }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongying7847 2015-02-18 13:10

    Why do you loop through the files? This one would be much easier:

    // 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 );
    
    评论
    解决 无用
    打赏 举报
  • dp518158 2015-02-18 13:18

    @unlink -> use unlink and if you don't see permission denied problem, the file and "dir" should be removed.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题