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.
Well, casting to an int will remove all non-numeric characters, so it doesn't really need to be escaped. Although, I sometimes do it for peace of mind :p
nemsis wrote:I really prefer using the first code because it's faster to code and to execute
Faster to execute: hardly. As in, I think posting this actually costed you more time than all your servers together will spend on mysql_real_escape_string execution during the rest of your life
Anyway, I would escape at all times. Just in case the int-restriction may be removed in the future, or if you (or someone else) ever copy this piece of code to another situation that is not strictly int, or whatever.
@mrvijayakumar: This is some very naive piece of code. I would not recommend anyone to use it. It doesn't trully solve the SQLi problem, while it introduces several more.
+1 to Apollo's advice. The only exception when you strictly need int casting is in the LIMIT clause of the SQL query.
For details, read this article, esp. chapters 4 and 5: http://www.webappsec.org/projects/artic ... 7.shtml#p4
Note:Please please don't forget to comment there for further improvements. Suggestions & ideas are warmly welcome. Thanks.
My comment is, for the love of $DEITY do not recommend this to anyone. If a beginner gets a hold of this they will be vulnerable and will waste valuable time troubleshooting their script.
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Too lazy to type that mysql_real_escape_string()? Me, too. It's time to learn OOP.
In my projects, escaping is always handled deep in the core and passing variables to the query is done through parameters. I have even made a scanner that checks no one has made code that enters variables elsewhere than the allowed parameters.
PDO is a useful library that is bundled within PHP. It allows you to do prepared statements easily.