[英]How to delete a file in a directory using PHP?
我正在嘗試使用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
希望有人能在這里發現我出錯的地方?
為什么要遍歷文件? 這個會容易得多:
// 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 );
首先通過打印整個文件路徑來調試文件路徑是否正常
// 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.