防止sql注入這些細節問題一般是出現在大意程序員或者是新手程序員了,他們未對用戶提交過來的數據進行一些非常過濾從而導致給大家測試一下就攻破了你的數據庫了,下面我來簡單的一個用戶登錄未進行安全配置可能出現的sql注入方法,下面一起來看看吧.
比如以下一段登錄的代碼:
- if($l = @mysql_connect('localhost', 'root', '123')) or die('數據庫連接失敗');
- mysql_select_db('test');
- mysql_set_charset('utf8');
- $sql = 'select * from test where username = "$username" and password = "$password"';
- $res = mysql_query($sql);
- if(mysql_num_rows($res)){
- header('Location:./home.php');
- //開源代碼Vevb.com
- }else{
- die('輸入有誤');
- }
注意上面的sql語句,存在很大的安全隱患,如果使用以下萬能密碼和萬能用戶名,那么可以輕松進入頁面,代碼如下:
1. $sql = 'select * from test where username = "***" and password = "***" or 1 = "1"';
很明顯,針對這條sql語句的萬能密碼是: ***" or 1 = "1
2. $sql = 'select * from test where username ="***" union select * from users/* and password = "***"';
正斜線* 表示后面的不執行,mysql支持union聯合查詢,所以直接查詢出所有數據; 所以針對這條sql語句的萬能用戶名是:***" union select * from users/*
但是,此注入只針對代碼中的sql語句,如果代碼如下:
$sql = "select * from test where username = $username and password = $password";
上面的注入至少已經不管用了,不過方法是一樣的;
在使用PDO之后,sql注入完全可以被避免,而且在這個快速開發的時代,框架橫行,已然不用過多考慮sql注入問題了.
下面整理了兩個防止sql注冊函數,代碼如下:
- /* 過濾所有GET過來變量 */
- foreach ($_GET as $get_key=>$get_var)
- {
- if (is_numeric($get_var)) {
- $get[strtolower($get_key)] = get_int($get_var);
- } else {
- $get[strtolower($get_key)] = get_str($get_var);
- }
- }
- /* 過濾所有POST過來的變量 */
- foreach ($_POST as $post_key=>$post_var)
- {
- if (is_numeric($post_var)) {
- $post[strtolower($post_key)] = get_int($post_var);
- } else {
- $post[strtolower($post_key)] = get_str($post_var);
- }
- }
- /* 過濾函數 */
- //整型過濾函數
- function get_int($number)
- {
- return intval($number);
- }
- //字符串型過濾函數
- function get_str($string)
- {//開源代碼Vevb.com
- if (!get_magic_quotes_gpc()) {
- return addslashes($string);
- }
- return $string;
- }
還有一些博客會這樣寫,代碼如下:
- <?php
- function post_check($post)
- {
- if (!get_magic_quotes_gpc()) // 判斷magic_quotes_gpc是否為打開
- {
- $post = addslashes($post); // 進行magic_quotes_gpc沒有打開的情況對提交數據的過濾
- }
- $post = str_replace("_", "\_", $post); // 把 '_'過濾掉
- $post = str_replace("%", "\%", $post); // 把' % '過濾掉
- $post = nl2br($post); // 回車轉換
- $post= htmlspecialchars($post); // html標記轉換
- return $post;
- }
- ?>
新聞熱點
疑難解答