Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i secure this PHP script?

I'm worried about sql injection, so 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'];
like image 769
Joshua Davis Avatar asked Dec 01 '25 01:12

Joshua Davis


2 Answers

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 https://www.php.net/mysql_real_escape_string and use it.

like image 80
Andrew Avatar answered Dec 02 '25 14:12

Andrew


$lastmsg = intval($_POST['lastmsg']);
like image 27
Dejan Marjanović Avatar answered Dec 02 '25 15:12

Dejan Marjanović



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!