適用於簡易 CMS、設定檔線上修改、模板編輯等場景。核心流程:讀取檔案內容 → 顯示於 textarea → 使用者修改送出 → 寫入檔案。注意:生產環境務必加入權限驗證、CSRF 保護、備份機制。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>檔案編輯器</title>
</head>
<body>
<form action="save_file.php" method="post">
<textarea name="file_contents" style="width:100%; height:600px; font-family:monospace;"><?php
$fileName = "config/settings.php"; // 目標檔案路徑
$handle = fopen($fileName, "r");
if ($handle) {
while (!feof($handle)) {
echo htmlspecialchars(fgets($handle)); // 防 XSS
}
fclose($handle);
}
?></textarea>
<input type="hidden" name="original_file_name" value="<?php echo $fileName; ?>" />
<input type="hidden" name="page" value="<?php echo $_SERVER['PHP_SELF']; ?>" />
<br><button type="submit">儲存變更</button>
</form>
</body>
</html>
<?php
session_start();
$file = $_POST['original_file_name'];
$content = $_POST['file_contents'];
$redirect = $_POST['page'];
// 基本安全檢查
$allowed_dir = __DIR__ . '/config/';
$real_file = realpath($file);
$real_allowed = realpath($allowed_dir);
if ($real_file === false || strpos($real_file, $real_allowed) !== 0) {
$_SESSION['error'] = '<span style="color:red">非法檔案路徑</span>';
header("Location: $redirect");
exit;
}
// 寫入檔案
$handle = fopen($file, "w");
if ($handle) {
if (fwrite($handle, $content) === false) {
$_SESSION['error'] = '<span style="color:red">寫入失敗</span>';
} else {
$_SESSION['error'] = '<span style="color:green">檔案儲存成功</span>';
}
fclose($handle);
} else {
$_SESSION['error'] = '<span style="color:red">無法開啟檔案</span>';
}
header("Location: $redirect");
?>
此基礎範例展示核心讀寫流程,實際部署請依專案安全需求完善防護機制。