Jump to content

Preventing MySQL injection attacks and Cross Site Scripting


milesap

Recommended Posts

I was wondering what is the best solution to prevent MySQL injection attacks and Cross Site Scripting. I devised the following which is placed before any PHP code can begin working on submitted variables:

 

if(isset($_GET)) {
foreach($_GET as $key => $value) {
	$_GET[$key] = htmlspecialchars(strip_tags($value));
}
}
if(isset($_POST)) {
foreach($_POST as $key => $value)
	{
		$_POST[$key] = htmlspecialchars(strip_tags($value));
}
}

 

Anyone have a better solution, or see any problems with using this?

 

I think, as someone mentioned in here before, it is better to "clean" the variable only when you are about to use it and it needs to be cleaned.  Don't clean it just to clean it.

 

 

 

So, only clean if you are using it in a sql statement, or if you are displaying it in html or a textbox.

 

I use this:

<?php
function clean($value, $type)
{
if ($type=="sql")
{
	// Stripslashes
	if (get_magic_quotes_gpc())
	  {
	  $value = stripslashes($value);
	  }
	  $value = mysql_real_escape_string($value);
}elseif ($type=="html")
{
	$value = htmlspecialchars($value, ENT_QUOTES);
}
return $value;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.