SQL Injection and how to prevent it

Associate
Joined
13 Nov 2003
Posts
1,567
Location
Manchester
Hi All

Working on a php based site and have heard about this sql injection thing.

Whats the best way to protect my forms from being exploited.

I have read loads of articles but they dont mean much to me lol

Aaron
 
Don't know about PHP, but in .net you can send parameters off with SQL commands which pretty much get rid of the need to worry about injection. e.g.

Code:
SELECT * FROM tbl WHERE id=@id;

Then you simply attach to that command object a parameter object telling you that @id=4839. If

Code:
3; DROP DATABASE chuckles;

is sent in the form, the parameter handles converting the input into a literal, and it never gets passed as a command. Like I said, worth looking into if there's something similar in PHP.

*edit* actually read the link - seems like there's some good functions there which negate having to do any regexps or anything like that.
 
that link scares me.

All I want to do is make this sql query injection proof.

$sql = "select * from adminusers where username='$username' and password='$userpass'";
 
hey mate

in both your username and password boxes type this:

' or 'x'='x

if your not checking the input the above will most likely let you in assuming your only checking if there is more than 0 records in the record set

if your on mysql i think you might have to change the query slightly:

" or "x"="x

don't know mysql but ive always thought basic queries were the same syntax.

having been a victim of sql injection, i have learnt how important it is to check EVERY input. you can even do it in a URL query string.

Check out "regular expressions" i use these to filter input. IE only allow characters a-z though. you will either get true or false with it. depending on that act upon it by stopping it before the sql query is executed and redirected them to the login page with a message - login.php?error=10
error 10 being an invalid character message or just bad login etc.

by the way im an ASP man myself, but the above principles still apply to PHP.
 
Code:
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

If doing things properly scares you, consider not doing them at all.
 
Back
Top Bottom