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

PHP实现网站目录最新文件展示并排除指定文件

提问:PHP筛选目录最新文件时排除指定文件并输出完整路径

我在网上找了一段PHP代码,折腾了好几个小时,想要实现两个功能:

  • 筛选目录里的最新文件时,排除mobile.htm文件
  • 输出文件的完整路径,这样后续可以把它转成链接

我一开始用的代码是这样的:

<?php $path = "states"; $latest_ctime = 0; $latest_filename = ''; $d = dir($path); while (false !== ($entry = $d->read())) { $filepath = "{$path}/{$entry}"; if(is_file($filepath) && filectime($filepath) > $latest_ctime) { $latest_ctime = filectime($filepath); $latest_filename = $entry; echo $latest_filename; ?>

自我解答:已解决问题,附可用代码

另外我还搞定了首页无法查看$var变量的问题——通过在首页添加iframe关联一个携带$_SESSION信息的页面就解决了。

针对筛选文件的需求,我调整后的代码可以正常工作了:核心是用if ($entry == "目标文件名") {continue;}语句跳过不想纳入筛选的文件,同时把$latest_filename赋值为完整的文件路径。

<?php $path = "states/$ls"; $latest_ctime = 0; $latest_filename = ''; $d = dir($path); while ($entry = $d->read()) { if ($entry == "mobile.htm") {continue;} if ($entry == "bg.jpg") {continue;} if ($entry == "flag.png") {continue;} $filepath = "$path/$entry"; $ctime = filectime($filepath); if (is_file($filepath) && $ctime > $latest_ctime) { $latest_ctime = $ctime; $latest_filename = $filepath; } } echo $latest_filename; ?>

这段代码的关键点:

  1. 新增了continue判断,跳过了mobile.htm以及其他我不需要的图片文件
  2. 将$latest_filename设置为$filepath(完整路径),输出后就能直接用来做链接了

感谢@Barmar的热心帮助!

内容的提问来源于stack exchange,提问作者Adam Tourgeman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:35:03