Hold Tight...

0 %
Driving cybersecurity excellence
Innovator behind Kodachi OS
  • Residence:
    ::0
  • Uptime Binary:
    110001
  • Mantra:
    Innovate, Secure, Repeat
ONS
EEDS
NSSG
Cybersecurity
Programming & R&D
Cryptocurrency
AI & vibe coding
  • Bash
  • Gambas
  • Delphi
  • PHP
  • Visual Basic
  • Rust

Sanitize data and prevent SQL injections in PHP

07/06/2013
2 min readDeep Tech8 code examplesUpdated October 2026

Key points

  • Sanitise every input before it reaches SQL or HTML: prepared statements (MySQLi or PDO) stop SQL injection, and escaping output stops XSS.
  • The 2013 mysql_* examples were removed in PHP 7.0; each one is followed by a PHP 8 version.
  • FILTER_SANITIZE_STRING is deprecated since PHP 8.1, so the string example has a PHP 8 replacement too.

Why Data Sanitization Matters: Prevent SQL Injections and XSS Attacks in PHP

Updated October 2026: Parts of this 2013 post on how to sanitize data and prevent SQL injections no longer run on PHP 7 or PHP 8, and one example was unsafe even then:

  • The mysql_* functions (mysql_query, mysql_real_escape_string) were deprecated in PHP 5.5 and removed in PHP 7.0 (I hit the same removals when moving from PHP 5.6 to 7.3). Use PDO or MySQLi prepared statements; I added both under the SQL example.
  • My SQL example escaped a whole query and then ran stripslashes(), which undoes the escaping. Escape or, better, bind values, never whole queries. addslashes() is not an SQL defence either.
  • FILTER_SANITIZE_STRING is deprecated since PHP 8.1. Escape text when you print it with htmlspecialchars($text, ENT_QUOTES, 'UTF-8'); I added a corrected cleaner under the string example.
  • stripslashes() was only needed for magic quotes, which PHP removed in 5.4.
  • Sanitizing is not validating: for a number or an email, check it with filter_var($v, FILTER_VALIDATE_INT) or FILTER_VALIDATE_EMAIL and reject it when the check fails.

The reason for adding this post is that sometimes, when I code in PHP, I forget that data has to be sanitized before execution to prevent SQL or XSS attacks. The simplest way to make SQL injection difficult is to use either MySQLi or PDO prepared statements, as they keep the SQL queries and data inputs wholly separated. You will find an example of each under SQL statements below.

Prepared statements and sanitizing functions I use

However, if you need to use data sanitization in regular PHP statements, here are some effective methods that I use:

  1. Prepared Statements with MySQLi: Use MySQLi prepared statements to ensure that SQL queries and data are processed separately, reducing the risk of SQL injection attacks.
  2. Prepared Statements with PDO: Similar to MySQLi, PDO (PHP Data Objects) also supports prepared statements, providing a secure way to handle SQL queries.
  3. Sanitizing Data in PHP:
    • Use functions such as htmlspecialchars() and strip_tags() to sanitize user inputs and prevent XSS attacks.
    • Validate and sanitize data before using it in SQL queries or displaying it on a web page.

By following these practices, you can significantly reduce the risk of SQL and XSS attacks in your PHP applications, ensuring that your data is handled securely.

Methods

Integer values:

PHP
// To SANITIZE Integer value use
$var=(filter_var($var, FILTER_SANITIZE_NUMBER_INT));

//example:
$theNumber="983928/2ddo@3233'0 or 1 '%^33)_23@''''$9123!@~#";
$theNumber=(filter_var($theNumber, FILTER_SANITIZE_NUMBER_INT));
echo $theNumber; 
//cleaned out put will be: 983928232330133239123
PHP

Email values:

PHP
//To SANITIZE email query value use
$var=(filter_var($var,  FILTER_SANITIZE_EMAIL));

//example:
$theEmail="warith@d\igi7/7.com";
$theEmail=(filter_var($theEmail,  FILTER_SANITIZE_EMAIL));
echo $theEmail;
//cleaned out put will be: warith@digi77.com;
PHP

String values:

PHP
//To SANITIZE String value use
function StringInputCleaner($data)
{
	//remove space before and after
	$data = trim($data); 
	//remove slashes
	$data = stripslashes($data); 
	$data=(filter_var($data, FILTER_SANITIZE_STRING));
	return $data;
}	
//example:
$myString="Welcome  here"; ;
$myString=StringInputCleaner($myString);
echo $myString;
PHP

FILTER_SANITIZE_STRING is deprecated since PHP 8.1 and the stripslashes() step was only for magic quotes, so on PHP 8 use this cleaner, which escapes the text for HTML output:

// FILTER_SANITIZE_STRING is deprecated since PHP 8.1: escape text when you output it instead
function StringInputCleaner($data)
{
	return htmlspecialchars(trim($data), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
//example:
$myString = "Welcome <b>here</b>";
echo StringInputCleaner($myString); // Welcome &lt;b&gt;here&lt;/b&gt;

SQL statements:

PHP
//To SANITIZE Sql query value use
function mysqlCleaner($data)
{
	$data= mysql_real_escape_string($data);
	$data= stripslashes($data);
	return $data;
	//or in one line code 
	//return(stripslashes(mysql_real_escape_string($data)));
}	

//example:
$insert="delete from vbtube_tubes WHERE tubeid =$row5[0]";
$insert= mysqlCleaner($insert);
mysql_query($insert);
PHP

The mysql_* functions above were removed in PHP 7.0, and escaping a whole query then calling stripslashes() undoes the escaping, so use a prepared statement instead (PDO or MySQLi):

// The mysql_* functions were removed in PHP 7.0: bind the value with a prepared statement instead

// PDO
$pdo = new PDO('mysql:host=localhost;dbname=vbtube;charset=utf8mb4', $dbUser, $dbPass, [
	PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$stmt = $pdo->prepare('DELETE FROM vbtube_tubes WHERE tubeid = ?');
$stmt->execute([(int) $row5[0]]);

// MySQLi
$db = new mysqli('localhost', $dbUser, $dbPass, 'vbtube');
$stmt = $db->prepare('DELETE FROM vbtube_tubes WHERE tubeid = ?');
$tubeId = (int) $row5[0];
$stmt->bind_param('i', $tubeId);
$stmt->execute();

Quick reference

PHP
mysql_real_escape_string //---> used when inserting into database.

htmlentities() //---> used when outputing data into web page.

htmlspecialchars() //---> used if u want to display the html tags and not execute them.

strip_tags() //---> used when remove html tags.

addslashes() //---> used when u need to add extra front slash for every back slash.

stripslashes() //---> remove slashes.
PHP

More sanitizing functions

PHP
FILTER_SANITIZE_NUMBER_FLOAT

FILTER_SANITIZE_SPECIAL_CHARS

FILTER_SANITIZE_STRING

FILTER_SANITIZE_URL

FILTER_SANITIZE_ENCODED
PHP

Posted in Deep TechTags: