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

如何用PHP显示挂载网络文件夹中最新4张图片?代码报错求助

问题描述

已通过符号链接挂载网络文件夹到路径/var/www/Access/images,编写PHP代码试图展示该目录下的图片,但页面显示破碎图片,怀疑是路径格式问题,代码如下:

<?php
  // Open the directory
  $dir = opendir('/var/www/Access/images');
  // Initialize an array to store the file names and last modified times
  $files = array();

  // Read the contents of the directory
  while (($file = readdir($dir)) !== false) {
    // Exclude the current and parent directories
    if ($file == '.' || $file == '..') continue;

    // Check if the file is a directory
    if (is_dir("/var/www/Access/images/'$file")) continue;

    // Get the last modified time for the file
    $lastModified = filemtime("/var/www/html/Access/images/'$file");

    // Add the file name and last modified time to the array
    $files[$file] = $lastModified;
  }

  // Close the directory
  closedir($dir);

  // Sort the array by last modified time
  asort($files);
  $files=array_reverse($files);
  // Initialize a counter
  $count = 0;

  // Iterate through the sorted array
  foreach ($files as $file => $lastModified) {
    // Display the image
    echo "<img src='/var/www/Access/images/'$file'>";

    // Increment the counter
    $count++;

    // Stop displaying images after the fourth one
    if ($count == 2) break;
  }
?>
解决方案

你的代码存在三个关键路径错误,逐一修正即可:

  • 路径中的多余单引号:is_dir和filemtime函数里的路径字符串错误添加了单引号,导致系统找不到对应文件。正确的路径应该直接拼接$file,不需要额外单引号包裹。
  • filemtime路径不一致:代码中filemtime使用的路径是/var/www/html/Access/images/,但实际目录是/var/www/Access/images/,多了html层级,需要修正为一致的路径。
  • img标签的src路径错误:浏览器无法识别服务器本地绝对路径/var/www/Access/images/,必须使用Web可访问的路径。假设你的网站根目录对应/var/www/html,需确保虚拟主机配置了/Access的访问映射,直接使用/Access/images/作为基础路径即可。

修正后的完整代码:

<?php
  // 打开目录
  $dir = opendir('/var/www/Access/images');
  // 初始化存储文件名和修改时间的数组
  $files = array();

  // 读取目录内容
  while (($file = readdir($dir)) !== false) {
    // 排除当前和上级目录
    if ($file == '.' || $file == '..') continue;

    // 跳过子目录
    $filePath = '/var/www/Access/images/' . $file;
    if (is_dir($filePath)) continue;

    // 获取文件最后修改时间
    $lastModified = filemtime($filePath);

    // 将文件名和修改时间加入数组
    $files[$file] = $lastModified;
  }

  // 关闭目录
  closedir($dir);

  // 按修改时间排序并反转(最新在前)
  asort($files);
  $files = array_reverse($files);
  // 初始化计数器
  $count = 0;

  // 遍历排序后的数组
  foreach ($files as $file => $lastModified) {
    // 输出图片,使用Web可访问路径
    echo "<img src='/Access/images/" . $file . "'>";

    // 计数器递增
    $count++;

    // 显示2张后停止
    if ($count == 2) break;
  }
?>

额外排查技巧:可以用var_dump(file_exists($filePath))验证文件是否存在,用echo $_SERVER['DOCUMENT_ROOT']确认网站根目录,确保Web路径配置正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 22:35:53