Skip to content

Instantly share code, notes, and snippets.

@Inndy
Created May 17, 2014 11:55
Show Gist options
  • Save Inndy/f7c318ba5fb4471f2ad3 to your computer and use it in GitHub Desktop.
Save Inndy/f7c318ba5fb4471f2ad3 to your computer and use it in GitHub Desktop.
DO NOT COPY THESE CODE IF YOU DON'T KNOW WHAT I'M DONING!!!
<?php // DO NOT COPY THESE CODE IF YOU DON'T KNOW WHAT I'M DONING!!!
/*
* 使用說明
*
* 在資料庫連結完成,並且設定編碼完成後再使用
*
* 先 defense_xss 再 defense_sql_injection
*
* 如果出現問題則先取消 defense_xss
* 如果還是有問題就跟我說
*
*/
function recursive_map($var, $func) {
// 遞迴處理陣列所有元素以及子陣列
if (gettype($var) === "array") {
foreach ($var as $k => $v) {
$var[$k] = recursive_map($v, $func);
}
return $var;
} else {
return $func($var);
}
}
function defense_sql_injection () {
// 針對所有輸入資料防禦 SQL Injection 攻擊
// mysql_query真的太多了,所以用這個方法一次處理所有資料
// 執行這裡之前必續確保資料庫已經建立連線,並且確定資料庫編碼已經設定成utf-8
// 也就是 mysql_query("SET NAMES 'utf8';", $link); 完成之後
// 不要重複
if (isset($GLOBALS['defensed_sql_injection'])) return;
$GLOBALS['defensed_sql_injection'] = true;
$_REQUEST = recursive_map($_REQUEST, mysql_real_escape_string);
}
function defense_xss () {
// 針對所有輸入資料防禦 XSS 攻擊
// 不要重複
if (isset($GLOBALS['defensed_xss'])) return;
$GLOBALS['defensed_xss'] = true;
$_REQUEST = recursive_map($_REQUEST, htmlspecialchars);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment