I'm worried about sql injection, so 开发者_Python百科how do i prevent it? I'm using this script but have had several people tell me its very insecure, if anyone can help by telling me how it would be great :).
source code:
if(isset($_POST['lastmsg']))
{
$lastmsg=$_POST['lastmsg'];
$result=mysql_query("SELECT * FROM updates WHERE item_id<'$lastmsg' ORDER BY item_id DESC LIMIT 16");
$count=mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
$msg_id=$row['item_id'];
$message=$row['item_content'];
Never, ever, put information from the user ($_POST
or $_GET
) directly into a query. If they are numbers, always convert them to integers first with (int)$var
or intval($var)
; if they are strings, always escape them with mysql_real_escape_string()
.
Read http://us2.php.net/mysql_real_escape_string and use it.
$lastmsg = intval($_POST['lastmsg']);
The best solution is migrating to mysqli_ or PDO and using prepared statements for your queries.
Make sure the magic_quotes_gpc
directive is disabled in your PHP configuration (PHP.ini).
If lastmsg is a string and you are using mysql, do this:
$lastmsg = mysql_real_escape_string($_POST['lastmsg']);
If lastmsg is a string and your DBMS does not have a native escape function, do this:
$lastmsg = addslashes($_POST['lastmsg']);
If lastmsg should be a number, check for that instead and don't do any escaping. You can use function is_numeric() and then cast the numeric string to an integer using intval().
You can simply add this :
$lastmsg=addslashes($_POST['lastmsg']);
for a larger scale you can use a more robust solution here is the function you can use
function escape_value($value) {
$magic_quotes_active = get_magic_quotes_gpc();
$new_php = function_exists("mysql_real_escape_string");
if ($new_php){
if ($magic_quotes_active){
$value = stripslashes($value);
}
$value = mysql_real_escape_string($value);
} else {
if(!$magic_quotes_active) { $value = addslashes($value); }
}
return trim($value);
}
mysql_real_escape_string is not always available so here is a work around
精彩评论