[英]Create subpages for each folder in current directory with PHP
我想為使用照相亭拍攝的照片創建下載頁面。 我希望每個活動都有一個自己的頁面,可以在其中查看和下載圖像。
為了避免重復代碼,我想創建一個下載頁面模板(單個 PHP 文件),它會掃描其目錄並為每個文件夾生成一個自己的頁面(包含 JPG 和 ZIP 文件)。 每個頁面都應該有不同的 URL。 HTML應該基本相同,只是顯示的文件和可下載的文件不同。 如何做到這一點?
我知道scandir()
function 但已經失去了如何為每個文件夾生成一個具有自己路徑的空頁面。
更新答案:
從測試來看,scandir 似乎會掃描指定目錄中的文件夾和文件的名稱,但除此之外什么都沒有。 您需要分幾個部分執行此操作。 第 1 部分,獲取主文件夾中的所有可用目錄,省略帶擴展名的實際文件:
<?php
$dir = 'path/to/current/directory/with/other/image/folders';
$files = scandir($dir); // get all files and folder names for this directory
$filecontents = file_get_contents('file_that_generates_gallery_and_download_links.php');
// Loop through files and figure out which ones are directories
foreach ($files as $file) {
$path_parts = pathinfo($file);
if ($path_parts['extension'] === null) {
file_put_contents( $dir . $path_parts['filename'] . '/filename.php', $filecontents);
}
}
?>
這負責為每個目錄/畫廊創建一個唯一的路徑。 新文件創建在與圖像相同的目錄中。 下一部分是創建上面代碼中引用的“file_that_generates_gallery_and_download_links.php”:
<?php
$dir = 'path/to/current/directory/with/images';
$files = scandir($dir);
$domain = 'https://yoursite.com'; // I hard-coded this value but do what makes since for your site's setup
$gallery = ''; // Used to hold the HTML for displaying the images and download links
// Loop through array of image files to create a "gallery", create an image tag for showing the image and an HTML download link beneath the image. Using download on the <a> tag tells the browser you want the user to download the file instead of linking to it.
foreach ($files as $file) {
$gallery .= '<div><img src="'.$domain . $file.'" alt=""><br><a href="'.$domain . $file.'" download>Download Image</a></div>';
}
?>
<div class="container">
<?php echo $gallery; ?>
</div>
這給了我以下 output 作為圖庫:
基於這個數組:
Array
(
[0] => file12345.png
[1] => file12345.png
[2] => file12345.png
[3] => file12345.png
[4] => file12345.png
[5] => file12345.png
[6] => file12345.png
[7] => file12345.png
[8] => file12345.png
[9] => file12345.png
[10] => file12345.png
[11] => file12345.png
[12] => ..
[13] => .
)
我當然用 CSS 為畫廊設計了樣式,並使用類來演示代碼如何動態構建圖像視圖和鏈接。 下載鏈接實際上也可以工作,圖像會立即下載。
我希望這比以前的反應更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.