PHP登入環節防止sql注入的方法淺析_PHP教程

來源:互聯網
上載者:User
在防止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');}else{die('輸入有誤');}

注意上面的sql語句,存在很大的安全隱患,如果使用以下萬能密碼和萬能使用者名稱,那麼可以輕鬆進入頁面:

$sql = 'select * from test where username = "***" and password = "***" or 1 = "1"';

很明顯,針對這條sql語句的萬能密碼是: ***" or 1 = "1

$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){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; } ?>

http://www.bkjia.com/PHPjc/824734.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/824734.htmlTechArticle在防止sql注入這些細節出現問題的一般是那些大意的程式員或者是新手程式員,他們由於沒有對使用者提交過來的資料進行一些必要的過濾,...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.