作者 leon0324 分享一個極簡的 PHP 線上文字編輯器,支援檔案讀取、編輯、儲存基本功能,程式碼精簡適合學習檔案操作與表單處理。
<?php
function write_file($filename, $contents) {
if ($fp = fopen($filename, "w")) {
fwrite($fp, stripslashes($contents)); // 移除魔術引號添加的斜線
fclose($fp);
return 1;
}
return 0;
}
if ($submitbutton == "完成") {
$rs = write_file("DownloadFilesa2001-12-15$page", $test);
echo "$page<br>";
} elseif ($action == "page") {
$content = "DownloadFilesa2001-12-15$page";
$fp = fopen($content, "r") or die("Could not open file.");
$contents = fread($fp, filesize($content)) or die("Could not read from file.");
$contents = htmlspecialchars($contents); // 防 XSS
fclose($fp);
// 輸出編輯表單 (原文 HTML 片段不完整,此處補全)
echo "<form method='post'>";
echo "<textarea name='test' rows='20' cols='80'>$contents</textarea><br>";
echo "<input type='hidden' name='page' value='$page'>";
echo "<input type='submit' name='submitbutton' value='完成'>";
echo "</form>";
} else {
// 檔案列表或首頁 (原文缺失)
echo "請選擇要編輯的檔案";
}
?>
?action=page&page=xxxfopen("r") → fread() → htmlspecialchars() 防 XSS → 顯示於 <textarea>stripslashes() 處理魔術引號 → fopen("w") → fwrite()$page 直接拼接路徑,攻擊者可傳入 ../../etc/passwd 讀寫任意檔案。必須用 basename() 或白名單驗證。stripslashes() 針對已棄用的 magic_quotes_gpc,現代 PHP (5.4+) 已移除,應檢查 get_magic_quotes_gpc() 再處理。header('Content-Type: text/html; charset=utf-8')。file_get_contents() / file_put_contents() 簡化讀寫。這是一個教學層級的極簡範例,展示 PHP 檔案操作基礎,但絕不可直接用於生產環境。現代開發請使用成熟的線上編輯器方案 (如 VS Code Server、Code-Server、PHP 版 File Manager 等)。