SQL注入式漏洞是許多PHP程序的主要安全危害,產生的原因是在向數據庫執行插入等語句時,web開發者允許最終用戶操作變量(例如根據表單提交內容顯示相應信息),通常是_GET、_POST或_SESSION等全局變量。
讓我們看以下的代碼:
以下為引用的內容: <?PHP
query = "Select news_title, news_text ";
query .= "FROM news";
query .= "Where news_id=". _GET['id'];
mysql_query(query);
?>
如果認為其中的_GET[‘id’]會永遠是個數值型的值那將是很嚴重的錯誤。最終用戶可以改變這個變量的值,例如"0; Delete FROM news;",那么query語句就會變成下面的值:
Select news_title, news_text FROM news Where news_id=0; Delete FROM news;
這將產生很嚴重的后果。
驗證數值型數據
數值型數據是最容易驗證的,PHP有一個自帶的函數叫 is_numeric()可以返回ture值來判斷是否是數值型,這個函數并不是MySQL自帶的,因此可在任何數據庫平臺的php程序中用于驗證數字。
下面是修改后的代碼:
以下為引用的內容: <?PHP
if (!is_numeric(_GET['id']))
{
// id's not numeric?
// kill the script before the query can run
die("The id must be numeric!");
}
query = "Select news_title, news_text ";
query .= "FROM news";
query .= "Where news_id=". _GET['id'];
mysql_query(query);
?>
驗證非數值型數據
非數值型數據的驗證稍有點麻煩。PHP有個叫Magic Quotes的特殊功能。當它激活時,PHP會自動過濾掉_GET和_POST全局變量中的反斜線符號(\),雙引號(”),單引號(’)和空白字符。問題是并不是所有的服務器都能打開了這個功能,所以必須檢測服務器是否開通了這個功能。可以使用get_magic_quotes_gpc()函數來判定 maigc quotes功能是否打開。
在MySQL查詢語句可以使用mysql_real_escape_string()函數來增強安全性,代碼如下:
以下為引用的內容: <?PHP
// Fix a _POST variable called firstName for MySQL
firstName = _POST['firstName'];
if (get_magic_quotes_gpc())
{
// If magic quotes is enabled - turn the string back into an unsafe string
firstName = stripslashes(firstName);
}
// Now convert the unsafe string into a MySQL safe string
firstName= mysql_real_escape_string(firstName);
// firstName should now be safe to insert into a query
?>
輸出到頁面
為正確顯示字符中的引號和反斜線,應使用stripslashes()函數
以下為引用的內容: <?PHP
firstName = _POST['firstName'];
if (get_magic_quotes_gpc())
{
// If magic quotes is enabled - turn the string back into an unsafe string
firstName = stripslashes(firstName);
}
// Now convert the unsafe string into a MySQL safe string
firstName = mysql_real_escape_string(firstName);
// Safe query
mysql_query("Insert INTO Names VALUES('". firstName ."')");
// Page output should look proper
echo "Hello ". htmlentities(stripslashes(firstName));
?>
最終整合
最后可以建立一個簡單的函數來解決在PHP中如果安全的進行MySQL查詢字符。值得注意的是,如果要輸出到WEB頁面上還需要使用stripslashes。
以下為引用的內容: <?PHP
function VerifyInput(input, forceInt = false)
{
if (is_numeric(input))
{
return input;
}
elseif (!forceInt)
{
if (get_magic_quotes_gpc())
{
// if magic quotes is enabled, get rid of those
// pesky slashes
input = stripslashes(input);
}
// convert the input variable into a MySQL safe string.
input = mysql_real_escape_string(input);
return input;
}
else
{
// if input not an integer and forceInt = true,
// kill script
die("Invalid Input");
}
}
// _POST['name'] should be a string
// _POST['id'] should be an integer, if not the script dies
id = _POST['id'];
name = _POST['name'];
query = "Update users SET name=". VerifyInput(name) ." ";
query .= "Where id=". VerifyInput(id, true);
// query should be safe to run
mysql_query(query);
?>

