How secure is this code??

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
vtvstv
Forum Newbie
Posts: 10
Joined: Sun May 24, 2009 3:19 am

How secure is this code??

Post by vtvstv »

Hi I am using the following code to prevent people from attacking through the input boxes via SQL injection, could you tell me if this is enough or am I still vulnerable.

Code: Select all

$username = addslashes($_REQUEST['username']);
$username = strip_tags($username);
$username = trim($username);
$password = addslashes($_REQUEST['password']);
$password = strip_tags($password);
$password = trim($password);
$username and $password are called into an sql SELECT command, so I don't want the data collected from the input boxes to allow for addition to the SQL statement.

Any thoughts will be greatly appreciated.

Kai
Last edited by vtvstv on Fri Jun 12, 2009 4:34 am, edited 2 times in total.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: How secure is this code??

Post by Benjamin »

:arrow: Moved to PHP - Security
User avatar
kaisellgren
DevNet Resident
Posts: 1675
Joined: Sat Jan 07, 2006 5:52 am
Location: Lahti, Finland.

Re: How secure is this code??

Post by kaisellgren »

Is your name Kai, too? Cool. :)

Just remove all that crap and use the database specific escaping function. I assume you are using MySQL, so, something like:

Code: Select all

$username = mysql_real_escape_string($_POST['username'],$link);
mysql_query("SELECT a FROM b WHERE c = '$username'");
Forget strip_tags(), it does not help you in terms of security. Maybe in some really rare cases. The same applies to trim(). Forget it. Addslashes() is just a general way to escape data, but it is not sufficient and the database specific function must be used.

Also, remember to enclose values within quotes. For example, in the above code I enclosed the $username value within single quotes. This is necessary.
User avatar
Darhazer
DevNet Resident
Posts: 1011
Joined: Thu May 14, 2009 3:00 pm
Location: HellCity, Bulgaria

Re: How secure is this code??

Post by Darhazer »

The appropriate place to escape variables is not where you are initializing it (getting the value from the request), but where you use them, because you can use the same variable for DB query and for output and you need to different escapes, to prevent both SQL injection and XSS
Post Reply