influx, I think that one needs to read up on overall PHP and MySQL security and not just look at one aspect of it.
There are several things important, like using quotes around values in a query in combination with mysql_escape_string() or mysql_real_escape_string().
Quote from MySQL general security manual page:
http://dev.mysql.com/doc/mysql/en/security-guidelines.html wrote:
A common mistake is to protect only string data values. Remember to check numeric data as well. If an application generates a query such as SELECT FROM table WHERE ID=234 when a user enters the value 234, the user can enter the value 234 OR 1=1 to cause the application to generate the query SELECT FROM table WHERE ID=234 OR 1=1. As a result, the server retrieves every record in the table. This exposes every record and causes excessive server load. The simplest way to protect from this type of attack is to use apostrophes around the numeric constants: SELECT * FROM table WHERE ID='234'. If the user enters extra information, it all becomes part of the string. In numeric context, MySQL automatically converts this string to a number and strips any trailing non-numeric characters from it.
You ask "why doesn't PHP automatically do it", well it does do an addslashes() when magic quotes is on. Most web hosts have this option on by default. So, you need to know those settings first before doing addslashes/mysql_escape_string manually. See this post of mine: http://www.phpbuilder.com/board/showpost.php?p=10648400&postcount=9
I don't see where $post_id is first set before here:
$post_id=mysql_real_escape_string($post_id);
If you're relying on register_globals being on, then turn it off for security reasons and program accordingly. That means using $GET, $POST, $_COOKIE, etc.
Remember that all HTML data comes across as strings. So, if you're expecting something numeric you can do it this way:
$code = isSet($_GET['code']) ? intval($_GET['code']) : 0;
$post_id = isSet($_GET['post_id']) ? intval($_GET['post_id']) : 0;
if ($post_id < 1 || $post_id > 5 || $code < 1 || $code > 2)
{
die('Invalid file ID/code. Please contact us if this problem persists.'); // or redirect to home
}
This is just a quick example and more needs to be in place but you get the idea. Note the intval() allows values like "12test" but makes it a number 12. So, remember that the $_GET value will still have "12test" in it. But it would assign zero if the input was this way: "test12".
I can see from the code snippet you posted that you have column names with "postx_name" (where 'x' is a number) and I think this is a wrong approach. Something like that should be a row value and not a column name. Make sure your database structure is done right to begin with and is normalized to at least the 3rd normal form. See this Introduction to Database Normalization page: http://dev.mysql.com/tech-resources/articles/intro-to-normalization.html
Look at the security links in my signature too.
hth.
🙂