简体   繁体   中英

How to delete a file in a directory using 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?

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”。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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