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

PHP 實作檔案線上編輯與儲存功能:讀取、修改、保存完整範例

     編輯:PHP 相關知識

線上編輯器核心功能實作

提供類似 IDE 的瀏覽器端檔案編輯功能,包含讀取檔案內容到編輯區與提交儲存回伺服器兩大核心操作。需嚴格限制可編輯目錄與檔案類型,防止任意檔案寫入漏洞。

安全性警示 ⚠️

  • 僅允許編輯指定目錄下的特定副檔名(.php、.html、.css、.js、.txt 等)
  • 必須驗證路徑不包含目錄穿越(../、..\\)
  • 生產環境建議加入身份驗證、操作日誌、IP 白名單
  • 重要配置檔(如 config.php、.env)應設為唯讀或排除編輯

讀取檔案頁面

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>線上檔案編輯器</title>
    <style>
        textarea { width: 100%; height: 500px; font-family: monospace; font-size: 14px; line-height: 1.5; }
        .actions { margin: 10px 0; }
        .msg { padding: 10px; margin: 10px 0; border-radius: 4px; }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
    </style>
</head>
<body>
    <h2>編輯檔案:<span id="filename"></span></h2>
    
    <form id="editForm" method="post" action="save_file.php">
        <input type="hidden" name="filepath" id="filepath">
        <textarea name="content" id="content" spellcheck="false"></textarea>
        <div class="actions">
            <button type="submit">儲存變更</button>
            <a href="file_manager.php">返回檔案管理</a>
        </div>
    </form>

    <script>
        // 從 URL 參數獲取檔案路徑(實際專案應從檔案管理器跳轉過來)
        const urlParams = new URLSearchParams(window.location.search);
        const filepath = urlParams.get('file');
        if(filepath){
            document.getElementById('filepath').value = filepath;
            document.getElementById('filename').textContent = filepath;
            // 載入檔案內容
            fetch('read_file.php?file=' + encodeURIComponent(filepath))
                .then(r => r.text())
                .then(text => document.getElementById('content').value = text)
                .catch(err => alert('讀取失敗:' + err));
        }else{
            alert('未指定檔案路徑');
            window.location.href = 'file_manager.php';
        }
    </script>
</body>
</html>

後端讀取處理

<?php
// read_file.php
header('Content-Type: text/plain; charset=UTF-8');

$baseDir = __DIR__ . '/editable_files'; // 僅允許編輯此目錄下的檔案
$allowedExt = ['php', 'html', 'htm', 'css', 'js', 'json', 'txt', 'md', 'xml', 'yml', 'yaml'];

$file = $_GET['file'] ?? '';
if(!$file) die('缺少檔案參數');

// 安全檢查
$realBase = realpath($baseDir);
$realFile = realpath($baseDir . '/' . $file);

if(!$realFile || strpos($realFile, $realBase) !== 0){
    http_response_code(403);
    die('禁止存取:路徑超出允許範圍');
}

$ext = strtolower(pathinfo($realFile, PATHINFO_EXTENSION));
if(!in_array($ext, $allowedExt)){
    http_response_code(403);
    die('禁止編輯此類型檔案');
}

if(!is_readable($realFile)){
    http_response_code(404);
    die('檔案不存在或不可讀');
}

readfile($realFile); // 直接輸出檔案內容,效率最高
?>

後端儲存處理

<?php
// save_file.php
header('Content-Type: application/json; charset=UTF-8');

$baseDir = __DIR__ . '/editable_files';
$allowedExt = ['php', 'html', 'htm', 'css', 'js', 'json', 'txt', 'md', 'xml', 'yml', 'yaml'];

$filepath = $_POST['filepath'] ?? '';
$content = $_POST['content'] ?? '';

if(!$filepath){
    echo json_encode(['success' => false, 'msg' => '缺少檔案路徑']);
    exit;
}

// 同樣的安全檢查
$realBase = realpath($baseDir);
$realFile = realpath($baseDir . '/' . $filepath);

if(!$realFile || strpos($realFile, $realBase) !== 0){
    echo json_encode(['success' => false, 'msg' => '禁止存取:路徑超出允許範圍']);
    exit;
}

$ext = strtolower(pathinfo($realFile, PATHINFO_EXTENSION));
if(!in_array($ext, $allowedExt)){
    echo json_encode(['success' => false, 'msg' => '禁止編輯此類型檔案']);
    exit;
}

// 可選:備份原檔
$backupFile = $realFile . '.bak.' . date('YmdHis');
if(!copy($realFile, $backupFile)){
    // 備份失敗不阻擋儲存,但記錄警告
    error_log("備份失敗: $backupFile");
}

// 寫入新內容
$bytes = file_put_contents($realFile, $content, LOCK_EX);
if($bytes === false){
    echo json_encode(['success' => false, 'msg' => '寫入失敗,請檢查權限']);
}else{
    echo json_encode(['success' => true, 'msg' => "儲存成功($bytes bytes)", 'backup' => basename($backupFile)]);
}
?>

功能擴展建議

  • 語法高亮:整合 CodeMirror、Monaco Editor 或 Ace Editor
  • 版本對比:儲存前顯示 Diff(可用 xdiff_string_diff 或 JS 庫)
  • 語法檢查:PHP 檔案儲存前執行 php -l 語法驗證
  • 權限控制:不同角色可編輯不同目錄
  • 操作審計:記錄誰在何時修改了哪個檔案、修改前後內容對比
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved