sql injection prevention

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
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

sql injection prevention

Post by SidewinderX »

PHP converts all GET/POST requests to strings, and almost every "tutorial" I've come across suggests using mysql_real_escape_string as prevention for sql injections. In almost all instances this is fine due to PHP's dynamic typing, but what precautions should I take if I want a request to be handled explicitly as a specific type other than a string? Would casting it to (int), (bool), (double) be secure?
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: sql injection prevention

Post by califdon »

SidewinderX wrote:PHP converts all GET/POST requests to strings, and almost every "tutorial" I've come across suggests using mysql_real_escape_string as prevention for sql injections. In almost all instances this is fine due to PHP's dynamic typing, but what precautions should I take if I want a request to be handled explicitly as a specific type other than a string? Would casting it to (int), (bool), (double) be secure?
mysql_real_escape_string is not the same as validating data for type or range. Start with defining clearly what you are trying to protect against. You may find this of value: http://www.w3schools.com/PHP/php_filter.asp (pertains to PHP 5 only)
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

Re: sql injection prevention

Post by SidewinderX »

Thank you califdon. I am trying to reinvent the wheel and emulate mysqli's prepared statements, which allows you to define the type of your inputs - i,s,d, and b (integer, string, float, and blob respectively). Since you can specify the type, I assumed it handled the sanitation differently.
User avatar
kaisellgren
DevNet Resident
Posts: 1675
Joined: Sat Jan 07, 2006 5:52 am
Location: Lahti, Finland.

Re: sql injection prevention

Post by kaisellgren »

Code: Select all

(int) $_GET['value'];
Is safe, however, it's best to always escape data you pass into a database.
Post Reply