Categories


Loading feed
Loading feed
Loading feed

PHP Security Tip #6


The topic of writing secure applications in PHP covers more than just writing good PHP code. Most applications make use of a database of some kind. Many times, vulnerabilities that affect the entire application, are introduced when building the SQL code. Today's Tip of the Day deals with one easy solution developers can implement.

When dealing with numbers in a SQL query, always cast.

Even if you are filtering your input, a good and easy to implement safety measure is to cast all numeric values in the SQL statement. Take for example the following code.


$myId = filter_var($_GET['id'],FILTER_VALIDATE_INT);
$sql = 'SELECT * FROM table WHERE id = '.$myId;


Even though you are applying the native PHP filters built into PHP 5.2, there is something additional you can do. Try this instead.


$myId = filter_var($_GET['id'],FILTER_VALIDATE_INT  );
$sql = 'SELECT * FROM table WHERE id = '.(int)$myId;


This final cast of the variable to an int removes any doubt about what will be passed to MySQL. The example above is purposefully simplified. In real-life situations, the code would be more complex and the chance for error much greater. By applying the final cast to in building the select statement, you are adding one more level of safety into your application.

Comments


Thursday, March 8, 2007
PREPARED STATEMENTS
2:58PM PST · pmuellr
SQL TYPE CASTING
8:35PM PST · pr0teus666
Friday, March 9, 2007
SQL TYPE CASTING DOESN'T WORK
10:47AM PST · jgandu
Tuesday, March 13, 2007
FILTER_VALIDATE_INT REALLY?
1:42AM PDT · sobstel
Sunday, May 27, 2007
FRENCH TRANSLATION
7:36AM PDT · neovov