Here is a function that I have used in providing multiple forms of sanitizing based on the context. Like people have mentioned, there is not one way to sanitize every type of content. You can use this or something like it and build upon it to suit your needs:
function sanitize($var, $type)
{
switch($type) {
case 'html':
$safe = htmlspecialchars($var);
break;
case 'sql':
$safe = mysql_real_escape_string($var);
break;
case 'file':
$safe = preg_replace('/(\/|-|_)/','',$var);
break;
case 'shell':
$safe = escapeshellcmd($var);
break;
default:
$safe = htmlspecialchars($var);
}
return $safe;
}
Here is an example of its use in a SQL query:
$query = sprintf("SELECT firstName FROM users WHERE userName = '%s'",
sanitize($_GET['userName'],'sql'));
Here is its use in HTML output:
<h1>Welcome <?php echo sanitize($firstName,'html');?></h1>
htmlentities? us2.php.net/manual/en/function.htmlentities.phpmysql_real_escape_stringis only for preparing data for use with the mysql extension, which is outdated, on its way to deprecation and shouldn't be used for new code. To prevent SQL injection, instead use prepared statements with PDO or mysqli, both of which have other important advantages over mysql.