PHP目录搜索并加载HTML文件<p>标签时网站崩溃问题咨询
问题分析与修复方案
你的代码导致网站冻结崩溃,核心问题集中在文件操作逻辑和资源处理上,以下是具体问题和修正方案:
关键错误点
- 文件路径错误:你用修改后的
$file(已转小写、替换符号、截取扩展名)去打开文件,这并非原文件的正确路径,应该用原始文件名$filecom加上目录$directory。 - 未读取文件内容:
fopen返回的是文件资源句柄,不是文件内容,直接传给strip_tags完全无效,还会造成资源泄漏。 - 逻辑顺序错误:先打开所有文件再判断是否匹配,会读取大量无关文件,占用过多资源导致网站崩溃。
- 缺少错误处理:没有判断文件是否成功打开,遇到无法读取的文件时会直接抛出错误中断程序。
修正后的代码示例
$directory = "test/"; if (isset($submitbutton) && !empty($searchoriginal) && is_dir($directory)) { if ($open = opendir($directory)) { if ($countsearchterms == 1) { $searchTerm = strtolower($search[0]); // 统一转小写,避免大小写匹配问题 while (($filecom = readdir($open)) !== false) { // 跳过系统默认的.和..目录 if ($filecom === '.' || $filecom === '..') { continue; } // 处理文件名用于搜索匹配 $fileName = strtolower($filecom); $fileName = str_replace(['-', '_'], ' ', $fileName); $position = strpos($fileName, "."); $fileNameWithoutExt = substr($fileName, 0, $position); // 先判断是否匹配,再读取文件,减少不必要的IO操作 if (strpos($fileNameWithoutExt, $searchTerm) !== false) { $displayName = ucwords($fileNameWithoutExt); echo "<a href='http://website here/$directory$filecom'>$displayName</a><br>"; // 读取并处理文件内容 $filePath = $directory . $filecom; if (file_exists($filePath) && is_readable($filePath)) { $fileContent = file_get_contents($filePath); // 提取<p>标签内容,strip_tags保留<p>标签 $pContent = strip_tags($fileContent, '<p>'); // 可选:截断内容,避免输出过多影响页面 $pContent = substr($pContent, 0, 200) . '...'; echo $pContent . "<br><br>"; } else { echo "无法读取文件内容<br><br>"; } } } closedir($open); } } }
额外优化建议
- 用
file_get_contents替代fopen+fread,代码更简洁,无需手动关闭文件资源。 - 若需要精准提取
<p>标签内容,可使用DOMDocument替代strip_tags,避免多余内容:
$dom = new DOMDocument(); @$dom->loadHTML($fileContent); // @忽略HTML解析时的非标准语法警告 $pTags = $dom->getElementsByTagName('p'); if ($pTags->length > 0) { echo $dom->saveHTML($pTags->item(0)) . "<br><br>"; // 只取第一个<p>标签内容 }
内容的提问来源于stack exchange,提问作者Hunt Computer help
相关产品推荐
相关产品推荐

