You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHPMailer触发file_get_contents(errno=21)错误但脚本功能正常,求解决

问题排查与修复方案

错误根源

scandir()函数会返回目标文件夹下的所有条目,包括.(当前目录)和..(上级目录)这两个特殊目录项。你的代码没有过滤这些目录,导致AddEmbeddedImage()尝试读取目录文件,触发了file_get_contents()的errno=21(Is a directory)错误。

修复步骤

  • 过滤特殊目录项:在循环开头直接跳过.和..,避免处理目录
  • 验证文件类型:确认当前条目是文件而非子目录,防止意外处理嵌套文件夹
  • 规范路径拼接:用DIRECTORY_SEPARATOR拼接路径,避免因文件夹末尾无斜杠导致的路径错误
  • 可选:过滤图片扩展名:只处理指定格式的图片文件,进一步避免无效文件

修正后的代码示例

$newFiles = scandir($mypath);
foreach($newFiles as $files19) {    
    // 跳过当前/上级目录
    if ($files19 === '.' || $files19 === '..') {
        continue;
    }
    
    // 拼接完整文件路径
    $filePath = $mypath . DIRECTORY_SEPARATOR . $files19;
    
    // 跳过非文件条目(比如子文件夹)
    if (!is_file($filePath)) {
        continue;
    }
    
    // 可选:只处理常见图片格式
    $allowedImageExts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    $fileExt = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
    if (!in_array($fileExt, $allowedImageExts)) {
        continue;
    }
    
    $cid_name = mt_rand(10,99);   
    $body .= "<img alt='PHPMailer' src='cid:$cid_name'> ";
    $mail->AddEmbeddedImage($filePath, $cid_name, $files19);
}   

内容的提问来源于stack exchange,提问作者Patrick Collins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 23:48:21