2012-02-19 35 views
-3

我是PHP新手,不確定我的代碼是否會阻止它受到任何SQL攻擊。而且,我對我爲什麼不能登錄感到困惑。它不會給我任何錯誤。此代碼是否可以防止SQL注入攻擊併爲何不起作用?

<?php 
$host="localhost"; // Host name 
$username="*****"; // Mysql username 
$password="****"; // Mysql password 
$db_name="***"; // Database name 
$tbl_name="electoral"; // Table name 

// Connect to server and select databse. 
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB"); 

// username and password sent from form 
$username=$_POST['username']; 
$password=$_POST['password']; 

// To protect MySQL injection (more detail about MySQL injection) 
$username = stripslashes($username); 
$password = stripslashes($password); 
$username = mysql_real_escape_string($username); 
$password = mysql_real_escape_string($password); 

$sql="SELECT * FROM $tbl_name WHERE username='$username' and password= md5('$password')"; 
$result=mysql_query($sql); 

// Mysql_num_row is counting table row 
$count=mysql_num_rows($result); 
// If result matched $myusername and $mypassword, table row must be 1 row 

if($count==1){ 
// Register $myusername, $mypassword and redirect to file "_____" 

session_register("username"); 
session_register("password"); 
header("location:electoralcommission.php"); 
} 

?> 

有什麼想法嗎?謝謝

+0

你是寫這個還是你從某處複製過? – 2012-02-19 23:46:03

+0

複製零碎 – 2012-02-19 23:46:36

+3

你的代碼在'<?php'之前是否真的有空格?如果是這樣,會話呼叫將失敗。 – 2012-02-19 23:48:00

回答

1

stripslahes()是不必要的,真的不是一個好主意使用。 mysql_real_escape_string()是首選的,如果你要逃避字符串,以防止注射。

就我個人而言,我建議您改用參數化查詢的PDO。參數化查詢遠遠比要記住是否正確轉義字符串要乾淨得多,再加上它至少與一些數據庫&驅動程序組合(特別是不確定PHP)有關,它將允許SQL服務器緩存部分查詢,爲了更好的性能(加上,我懷疑mysql _...是否接近於快速!)。有關更多信息(或許多其他問題),請參閱this stack overflow page

+0

我並不完全確定,但某些版本的MySQL無法緩存準備好的語句。 – arthurprs 2012-02-20 00:15:05

+0

無論如何PDO模擬默認準備。嘆。 – Charles 2012-02-20 15:29:34

相關問題