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

PHP 安全程式設計核心觀念:輸入驗證、檔案寫入風險與最佳實踐

     編輯:PHP 綜合知識

為什麼安全要從寫代碼時就考慮

最有效阻止惡意破壞的方法是在開發階段預判風險,而非事後修補。以下以簡化檔案寫入的函數為例,說明潛在隱患。

高風險函數範例

<?php
function write_text($filename, $text = "") {
    static $open_files = array();

    if ($filename == NULL) {
        foreach ($open_files as $fr) fclose($fr);
        return true;
    }

    $index = md5($filename);
    if (!isset($open_files[$index])) {
        $open_files[$index] = fopen($filename, "a+");
        if (!$open_files[$index]) return false;
    }
    fputs($open_files[$index], $text);
    return true;
}
?>

實際攻擊場景

前端表單 quotes.php 允許用戶提交引言並儲存:

<form action="" method="get">
  選擇類別: <select name="quote">
    <option value="funny">幽默</option>
    <option value="political">政治</option>
    <option value="love">愛情</option>
  </select><br>
  內容: <input type="text" name="quote_text" size="30">
  <input type="submit" value="儲存">
</form>

<?php
include_once('write_text.php');
$filename = "/home/web/quotes/{$_GET['quote']}"; // 直接帶入用戶輸入!
$quote_msg = $_GET['quote_text'];
if (write_text($filename, $quote_msg)) {
    echo "引言已儲存!";
} else {
    echo "寫入失敗";
}
write_text(NULL);
?>

漏洞分析

  • 路徑遍歷:用戶提交 quote=../../etc/passwd 可寫入系統敏感檔案。
  • 任意檔案寫入:結合 NULL byte(PHP < 5.3.4)可截斷副檔名限制。
  • 無輸入驗證:未檢查 quote 是否為預期值(funny/political/love)。

修正原則

  1. 白名單驗證:if (!in_array($_GET['quote'], array('funny','political','love'))) die('非法類別');
  2. 路徑正規化:$filename = realpath("/home/web/quotes/" . basename($_GET['quote'])); 確保在預期目錄下。
  3. 權限最小化:Web 使用者僅擁有特定目錄寫入權限。
  4. 關閉錯誤顯示:生產環境 display_errors = Off,記錄至日誌。
  5. 使用預處理語句:資料庫操作防 SQL 注入。
  6. 輸出編碼:htmlspecialchars() 防 XSS。

總結

安全不是功能,而是開發流程的一部分。每個變數進入系統前都要問:來源?預期格式?邊界條件?如何失敗?

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