请求帮助实现PHP视频画廊的递归文件夹搜索功能
Solution for Recursive Video Gallery (No External Dependencies)
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 yourgallerydirectory, skipping the.and..system folders to avoid infinite loops. - Path Handling: Instead of just grabbing the filename, we calculate the relative path from the
galleryroot (e.g.,summer-videos/beach.mp4). This ensures the<video>tag'ssrcattribute 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
相关产品推荐
相关产品推荐

