简体   繁体   English

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

[英]How to delete a file in a directory using PHP?

I'm trying to delete a given file from a directory using PHP. 我正在尝试使用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 我可以确认文件61514.png肯定在目录some/dir

Hoping someone can spot where I'm going wrong here? 希望有人能在这里发现我出错的地方?

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

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

@unlink - >使用unlink,如果你没有看到权限被拒绝的问题,应该删除文件和“dir”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM