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

PHP + AJAX 實作類 Windows 檔案管理系統(四)建立資料夾與貼上/移動邏輯

     編輯:PHP 相關知識

PHP + AJAX 實作類 Windows 檔案管理系統(四)建立資料夾與貼上/移動邏輯

本篇解析 rename.php 中的 Createfolder()、Past() 以及遞迴複製函式 full_copy()。

1. 建立資料夾 Createfolder()

function Createfolder($path, $nname) {
    if (is_dir($path) && is_writable($path)) {
        if (preg_match("/^\w{1,255}$/i", $nname)) { // 僅允許字母數字底線
            echo mkdir($path . "/" . $nname, 0777) ? 'Create Folder success' : 'Create Folder Fail';
        } else {
            echo "Folder Error";
        }
    } else {
        echo "Can't Create Error file not is_writable or not dir";
    }
}
  • 路徑需為可寫目錄。
  • 名稱以正則 ^\w{1,255}$ 限制,防止注入特殊字元。
  • 0777 權限受 umask 影響,實際權限可能較低。

2. 貼上/移動 Past()

function Past($currentpath, $currentfilename, $filepote) {
    $str = substr($currentfilename, -1, 1);
    if ($str == "|") { // 以 | 區隔標記「剪下」操作
        $currentfilename = str_replace("|", "", $currentfilename);
        $filepote = str_replace("|", "", $filepote);
    }

    if (is_dir($currentpath) && is_writable($currentpath) && is_dir($filepote) && is_writable($filepote)) {
        // 目錄複製
        $t = full_copy($filepote, $currentpath . "/" . $currentfilename) ? 't' : 'f';
    } elseif (is_file($filepote) && file_exists($filepote)) {
        // 檔案複製
        if (file_exists($currentpath . $currentfilename)) { echo 'file exists! plase rename it!'; exit; }
        echo copy($filepote, $currentpath . $currentfilename) ? 'success' : 'error';
    }

    // 若為剪下且複製成功,刪除來源
    if ($str == "|" && $t == 't') {
        deldir($filepote);
    }
}
  • 前端以 | 尾碼區分「複製」與「剪下」。
  • 目錄採遞迴複製,檔案直接 copy()。
  • 目標同名檔案存在時中止,要求使用者先重命名。

3. 遞迴複製目錄 full_copy()(來源:PHP 官方範例)

function full_copy($source, $target) {
    if (is_dir($source)) {
        @mkdir($target);
        $d = dir($source);
        while (FALSE !== ($entry = $d->read())) {
            if ($entry == '.' || $entry == '..') continue;
            $Entry = $source . '/' . $entry;
            if (is_dir($Entry)) {
                full_copy($Entry, $target . '/' . $entry);
            } else {
                copy($Entry, $target . '/' . $entry);
            }
        }
        $d->close();
    } else {
        copy($source, $target);
    }
}

標準遞迴演算法,逐項建立子目錄並複製檔案。大量檔案時可能超時,建議改用 RecursiveIteratorIterator + FilesystemIterator (SPL) 或系統指令 cp -r。

安全性補充

  • 所有路徑參數未做 realpath() 限制,易遭目錄遍歷攻擊。
  • 缺乏 CSRF 保護,建議加入一次性 Token 驗證。
  • 錯誤訊息直接 echo,前端以字串比對,建議改回傳 JSON 結構。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved