首页 > 解决方案 > 发送 PHPMailer 电子邮件后删除“附件”文件夹

问题描述

我有一个 Web 表单,其中每个用户都有一个唯一的上传文件夹(使用他们的 PHP session_id() 作为文件夹名称),效果很好。提交表单时(经过错误检查)PHPMailer 用于发送电子邮件和附件。这也运作良好。但是,在发送电子邮件后,我想从文件夹中删除上传内容,然后是文件夹本身(有点像自我清理!)文件按预期删除,但文件夹仍然存在(尽管是空的)。我想知道该文件夹是否以某种方式“仍在使用”所以不会被删除或类似的东西?这是代码:

            // Empty the contents of the upload folder
            if (is_dir($dir)) { // Target directory ($dir) is set above in photos POST section
                // Check for any files inside the directory
                $files = glob($dir.'/*'); // Get all file names
                foreach($files as $file) { // Iterate through the files
                    if(is_file($file)) { // Check its a file
                        unlink($file); // Delete the file
                    }
                }
                // Remove the upload folder
                rmdir($dir); //NOT WORKING? NEEDS SOME TROUBLESHOOTING...
            }

关于为什么保留此文件夹的任何其他想法?

标签: phpphpmailer

解决方案


我猜你的文件夹可能包含默认 glob 模式不匹配的.隐藏文件(以 开头),所以试试这个:

$files = glob($dir . '/{,.}*'); // Get all file names including hidden ones
foreach($files as $file) { // Iterate through the files
    if(is_file($file)) { // Check its a file
        unlink($file); // Delete the file
    }
}

还要检查 unlink 和 rmdir 的返回值,这样你就可以准确地看到它失败的地方。


推荐阅读