Securing PHP Form Data from hackers
I recently had a hacker try to gain access to our database. This attack prompted me to revisit the security placed on the site. When you use forms in your website, you have to protect them from hackers who will seek to gain access to send emails or insert spam links into your web site. There are a few steps you can take to prevent this from happening. Not doing so will pretty much assure that sooner or later your site will get attacked by a hackers robot code.
Below is the code I use to strip all posted data. Some of this code I wrote and some of it was provided to me by a good friend. This function is a good place to start with your security.
// This function removes potential strings which can be used by a hacker to gain control of your server.
function escape_data ($data)
{
if($data){
// --------------------------------------------------------------------------
// Check if Magic Quotes are enabled.
// --------------------------------------------------------------------------
if (ini_get('magic_quotes_gpc'))
{
$data = stripslashes($data);
}
// --------------------------------------------------------------------------
// Check for mysql_real_escape_string support.
// --------------------------------------------------------------------------
if (function_exists('mysql_real_escape_string'))
{
global $dbc; // Need the connection.
//$data = mysql_real_escape_string (trim($data), $dbc);
$data = mysql_real_escape_string (trim($data));
}
else
{
$data = mysql_escape_string (trim($data));
}
// --------------------------------------------------------------------------
// Now deal with idiots who attempt to perform a cross-site scripting
// attack by filtering the string.
// --------------------------------------------------------------------------
$data = htmlentities ($data);
// --------------------------------------------------------------------------
// Return the filtered data string back to the caller.
// --------------------------------------------------------------------------
return $data;
}
} // End of function.
The usage of this is as follows. This should be done on all data that comes from the form.
$visitor = escape_data($_POST['visitor']); $visitormail = escape_data($_POST['visitormail']); $notes = escape_data($_POST['notes']); $attn = escape_data($_POST['attn']);
When ever you capture data, you should also get the users IP address and record that as well. If you do have problems, you then know where the hacker came from and can block that IP address and notify the users ISP.
//Get the users IP Address
function VisitorIP(){
if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$TheIp=$_SERVER['HTTP_X_FORWARDED_FOR'];
else $TheIp=$_SERVER['REMOTE_ADDR'];
return trim($TheIp);
}
$IP = VisitorIP();
if(!$IP){
$IP='IP Blocked';
}