开发者

prevent/secure database entires from users

I am new to sql how do i make this code more secure from sql injection and over wrong doing.

// Variables 
$db_host = 'localhost'; 
$db_user = 'user'; 
$db_pass = 'pass'; 
$db_name = 'db'; 

$Username = $_POST['username']; 
$Email    = $_POST['email'];     

// DB Connect
$connect = mysql_connect( $db_host, $db_user, $db_pass ) or die( mysql_error() ); 
$connection = $connect; 

mysql_select_db( $db_name, $connect ) or die( mysql_error() ); 

// Inserting into DB 
$qInsertUser = mysql_query(" INSERT INTO `database` (`id`, `username`, `email`) VALUES ( ``, `$Username`, `$Email`) ");开发者_如何学JAVA 

if ($qInsertUser){ 
    echo "You are now subscribed to our newsletter. Thank you!"; 
} else { 
    echo "Error!"; 
}


You should probably use prepared statements. Instead of:

$qInsertUser = mysql_query(" INSERT INTO `database` (`id`, `username`, `email`) VALUES ( ``, `$Username`, `$Email`) "); 

Replace it with a prepared statement and execution:

$sth = $dbh->prepare('INSERT INTO `database` (`id`, `username`, `email`) VALUES (?, ?, ?)');
$sth->execute(array($id, $username, $email));

Let the libraries handle all the quoting for you.


Make sure you are escaping the values. Rather than:

$Username = $_POST['username']; 
$Email    = $_POST['email'];    

try this:

$Username = mysql_real_escape_string($_POST['username']);
$Email = mysql_real_escape_string($_POST['email']);

Please note that this answer is by no means meant to be an exhaustive anti-SQL-injection resource, but hopefully it will get you going on the right track.


Beside mysql_real_escape_string, also try to validate the input. users shouldn't be allowed to enter whatever. use regexp syntax and type casting or settype. this I mean on server side in php. javascript validations are not enough I've seen many programmers and webmasters spend more energy on js validation while in php they write no validation at all.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜