首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 簡易 Web 文件分享腳本:目錄掃描、中文編碼、下載鏈接生成

     編輯:PHP 相關知識

一個單文件 PHP 腳本,放入目錄即可通過 Web 瀏覽/下載該目錄下所有文件(排除自身),支援中文文件名、空格編碼、UTF-8/GBK 自動轉換。

完整代碼(index.php)

<?php
// 配置區
$hide_files = ['index.php', '.git', '.htaccess', 'Thumbs.db']; // 隱藏文件
$encoding_detect = ['UTF-8', 'GBK', 'BIG5']; // 文件名編碼嘗試順序

// 掃描目錄
$files = [];
$dir = __DIR__;
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
    if ($file === '.' || $file === '..') continue;
    if (in_array($file, $hide_files, true)) continue;
    if (is_dir($dir . '/' . $file)) continue; // 可選:遞歸顯示子目錄

    $files[] = $file;
}
closedir($dh);

// 自然排序(數字感知)
natsort($files);




    
    文件分享 - <?= htmlspecialchars(basename($dir)) ?>
    
    


    

📁

目錄為空

    0) { $display_name = $try; break; } } ?>
= 1024 && $i < count($units) - 1) { $bytes /= 1024; $i++; } return round($bytes, 2) . ' ' . $units[$i]; }

關鍵技術點解析

  1. 目錄掃描:opendir/readdir 比 scandir 記憶體友好(大目錄);
  2. 自然排序:natsort() 讓 file2.txt 排在 file10.txt 前;
  3. 中文文件名 URL 編碼:rawurlencode() (RFC 3986) 優於 urlencode(),空格編為 %20 而非 +;
  4. 編碼自動檢測:嘗試 iconv 從 GBK/BIG5 轉 UTF-8,解決舊系統上傳文件名亂碼;
  5. 安全性:htmlspecialchars() 防 XSS,rel="noopener" 防標籤劫持;
  6. 單文件部署:無依賴、無配置、放入即用。

進階擴展建議

  • 密碼保護:if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_PW'] !== 'secret') { header('WWW-Authenticate: Basic realm="Private"'); header('HTTP/1.0 401 Unauthorized'); exit; };
  • 子目錄瀏覽:遞歸掃描 + 路徑參數 ?dir=sub,需防目錄遍歷 realpath() 校驗;
  • 文件預覽:圖片/PDF/文本在線預覽,mime_content_type() 判斷;
  • 上傳功能:POST 表單 + move_uploaded_file(),限制類型/大小;
  • Nginx 加速:location /files/ { internal; alias /data/files/; } + PHP 簽名 URL(X-Accel-Redirect)。

部署注意事項

  1. 文件保存為 UTF-8 無 BOM 編碼;
  2. 目錄權限:PHP 進程需讀取權限(www-data 用戶);
  3. 隱藏敏感文件:.env、config.php、.git 等加入 $hide_files;
  4. 大文件下載:PHP 直接輸出會佔用記憶體,生產環境用 X-Sendfile/X-Accel-Redirect 交給 Web 服務器。

這個腳本適合臨時文件分享、內網資源發佈、靜態站點目錄索引,零配置即用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved