Welcome to WebmasterWorld Guest from 54.144.3.134

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

SQL injections how to write against them

sql injections

     
9:13 pm on Jul 23, 2007 (gmt 0)

New User

5+ Year Member

joined:Nov 13, 2006
posts:20
votes: 0


I want to know how to prevent or try to resist sql injections in my code. I filter our everything except text in most of my forms but most use htmlspecialchars. Should I not use that?

Should I limit the amount of data input?

I mean what is everyone else doing that works?

9:21 pm on July 23, 2007 (gmt 0)

Senior Member

WebmasterWorld Senior Member eelixduppy is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Nov 12, 2005
posts:5966
votes: 0


The number one thing you really have to do is to escape your query variables. To do this, you can use mysql_real_escape_string [php.net] or mysql_escape_string [php.net].
9:25 pm on July 23, 2007 (gmt 0)

Junior Member

10+ Year Member

joined:Apr 26, 2004
posts:137
votes: 0


Any input field should have the addslashes() function put around the variable when building your sql command.

for example:

$reference = $_REQUEST['reference']

... use $reference in you code as usual...

$sql= "SELECT count(*) FROM track_page WHERE session_index='$session_index' AND reference='".addslashes($reference)."'";
$result = @mysql_query($sql);

Likewise, when you retrieve that data to display back to the user you may want to add htmlspecialchars($reference) around the code.

You can test your input fields by entering '

* I really would not reccomend using magic_quotes.

9:32 pm on July 23, 2007 (gmt 0)

Senior Member

WebmasterWorld Senior Member eelixduppy is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Nov 12, 2005
posts:5966
votes: 0


Just a quick note: addslashes shouldn't be used unless you cannot use the functions I linked to above. Not only are additional characters escaped with those functions but in the case of mysql_real_escape_string, the charset of the database is used, as well.
9:54 pm on July 23, 2007 (gmt 0)

Full Member

5+ Year Member

joined:July 13, 2007
posts:235
votes: 0


SQL injection depends a lot on what version of SQL you're using--mysql_real_escape_string is definitely the best choice if you're using MySql, but for Microsoft SQL Server you can use...

str_replace( "'", "''", $evilInput );

Microsoft SQL interprets two single quotes ('') as a single escaped quote.

[edited by: WesleyC at 9:55 pm (utc) on July 23, 2007]

4:06 am on July 24, 2007 (gmt 0)

New User

5+ Year Member

joined:Nov 13, 2006
posts: 20
votes: 0


I use only php and mysql on my applications.