Tuesday, 14 April 2015

What is Best method for sanitizing user input with PHP?

What is  Best method for sanitizing user input with PHP

Sanitize user-input when using in Mysql Query.
You can use real_escape_string of mysqli.
For Example:
$mysqliObj = new mysqli("localhost", "root", "", "mydb");
$city = $mysqliObj->real_escape_string($_POST['city']);
if ($mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", $mysqli->affected_rows);
}



Sanitize user-input  while insert in database and displaying in Browser.
You can use htmlentities and html_entity_decode.
For Example:
echo htmlentities($data['description']);//at the time of insert in database 
echo html_entity_decode($data['description']); //at the time of display in browser from database



Sanitize user-input when using in Command Prompt.
You can use escapeshellarg.
For Example:
system('ls '.escapeshellarg($data['dir']));