Mysql injection protection

Hi guys,

I am trying to secure a user submitted form and guard against header injection before MYSQL insert.

I have found these 3 examples on the net, not sure which one to use and what else I need to protect from? I will also be letting users upload a picture. I am also using these validation checks:


 if(($_SESSION['security_code'] !== $_POST['security_code']))  {
      
	  $errors[] ="Sorry, you have provided an invalid security code"; 
   }

// First, make sure the form was posted from a browser.   
	if(!isset($_SERVER['HTTP_USER_AGENT'])){ 
	
	$errors[] ="Possible header injection attack"; 	
} 

I was hoping for an efficiant way to sanitize posted form data without using excessive code that i can use on this and future applications.

Any help would be greatly appreciated :slight_smile:

Example 1


<?

foreach($_POST as $key=>$value) 
        {                  
	if (get_magic_quotes_gpc())     
            {         
            $_POST[$key]=stripslashes($value); 
            }         
 	$_POST[$key] =mysql_real_escape_string($_POST[$key]);
        } 

echo $query = "INSERT INTO table (something, somethingelse) VALUES ('".$_POST['itema']."', '".$_POST['itemb']."')";  

?>

Example 2



<?php

//Function to sanitize values received from the form. Prevents SQL injection
function clean($str)
{

$str = @trim($str);

if(get_magic_quotes_gpc())
	{
	$str = stripslashes($str);
	}

return mysql_real_escape_string($str);
}

//values received from form
	$category = clean($_POST['Categoryname']);
	$subcategory = clean($_POST['SubCategoryName']); 

	// is there another way to do this raher than declaring each posted variable?
?> 


Example 3


//Function to sanitize values received from the form. Prevents SQL injection
            function clean($str) {
                $str = @trim($str);
                if(get_magic_quotes_gpc()) {
                    $str = stripslashes($str);
                }
                return mysql_real_escape_string($str);
            }
    
 //Sanitize the POST values
            $title = clean($_POST['title']);
            $description = clean($_POST['description']);
            // is there another way to do this raher than declaring each posted variable?

thanks for the tip :slight_smile:

rmysqli is a type, felgall meant mysqli.

I prefer the PDO library, it’s newer than the mysqli functions. I’d suggest playing with both though, to see which one you feel more comfortable with.

Thanks for the reply.
What is 'rmysqli ’ ?? I couldnt find any reference on the net?

but using prepare statements means that there is no way the data can end up being run as SQL.
so which one is best to use?

The simplest way to make SQL injection impossible is to use eithe rmysqli or PDO prepare statements so as to keep the SQL and data completely separated.

You still need to asanitise/validate the data but using prepare statements means that there is no way the data can end up being run as SQL.