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

PHP 安全防護核心原則:輸入過濾與清理實戰

     編輯:PHP 相關知識

核心原則:不信任外部資料

所有非程式碼直接寫入的資料(GET、POST、資料庫、Cookie、Session)均視為「有瑕疵」。

危險範例

$myUsername = $_POST['username']; // 受污染
$arrayUsers = array($myUsername, 'tom', 'tommy'); // 陣列也受污染
define("GREETING", 'hello ' . $myUsername); // 常數也受污染

解決方案:建立清理函數

function cleanInput($input) {
    $clean = strtolower($input);
    $clean = preg_replace("/[^a-z]/", "", $clean); // 僅保留小寫字母
    $clean = substr($clean, 0, 12); // 限制長度
    return $clean;
}

$myUsername = cleanInput($_POST['username']); // 乾淨
$arrayUsers = array($myUsername, 'tom', 'tommy'); // 乾淨
define("GREETING", 'hello ' . $myUsername); // 乾淨

關鍵建議

  1. 永遠在使用外部資料前先清理。
  2. 客戶端驗證(JS)只能提升體驗,無法替代伺服器端清理。
  3. 使用白名單(允許字符)而非黑名單(禁止字符)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved