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

请求帮助实现PHP视频画廊的递归文件夹搜索功能

Hey Paul, I feel your pain with those late-night debugging sessions—let's fix this recursive video gallery issue for you, keeping your no-external-resources requirement intact.

Your original code works great for a single folder, but since your videos are nested in subfolders, we need to replace the simple glob() call with a recursive directory traversal. Here's a modified version of your code that handles subfolders properly:

<div id="vid-gallery">
<?php
// (A) RECURSIVELY GET ALL VIDEO FILES FROM GALLERY AND SUBFOLDERS
$galleryRoot = __DIR__ . DIRECTORY_SEPARATOR . "gallery" . DIRECTORY_SEPARATOR;
$videos = [];

// Recursive function to scan folders
function scanVideos($dir, $galleryRoot, &$videos) {
  $items = scandir($dir);
  foreach ($items as $item) {
    // Skip parent/self directory markers
    if ($item === "." || $item === "..") continue;
    
    $fullPath = $dir . DIRECTORY_SEPARATOR . $item;
    // If it's a subfolder, scan it recursively
    if (is_dir($fullPath)) {
      scanVideos($fullPath, $galleryRoot, $videos);
    } 
    // If it's a video file, add to our list
    else {
      $ext = strtolower(pathinfo($fullPath, PATHINFO_EXTENSION));
      if (in_array($ext, ["webm", "mp4", "ogg"])) {
        // Calculate relative path from gallery root for the video src
        $relativePath = str_replace($galleryRoot, "", $fullPath);
        $videos[] = $relativePath;
      }
    }
  }
}

// Start scanning from the gallery root
scanVideos($galleryRoot, $galleryRoot, $videos);

// (B) OUTPUT ALL VIDEOS
if (count($videos) > 0) {
  foreach ($videos as $vidPath) {
    // Use rawurlencode to handle special characters in paths/filenames
    printf("<video src='gallery/%s' preload='auto'></video>", rawurlencode($vidPath));
  }
}
?>
</div>

Key Changes Explained:

  • Recursive Scanning: The scanVideos() function digs into every subfolder under your gallery directory, skipping the . and .. system folders to avoid infinite loops.
  • Path Handling: Instead of just grabbing the filename, we calculate the relative path from the gallery root (e.g., summer-videos/beach.mp4). This ensures the <video> tag's src attribute correctly points to nested files.
  • File Filtering: We check the file extension directly to target only your supported video types—no external libraries or plugins required.
  • Special Character Support: rawurlencode() handles spaces, accents, or other weird characters in filenames/paths, so your videos load correctly every time.

This should pull all your videos, no matter how deep they're nested in subfolders. Let me know if you run into any odd edge cases!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 13:37:48