Rize S. answered 03/23/23
Senior IT Certified Trainer, IT Developer & DBA Administrator
Sanitizing user input is a critical aspect of web application security, and there are a few best practices to keep in mind:
- Use prepared statements and parameterized queries when interacting with databases to prevent SQL injection attacks.
- Use htmlentities or htmlspecialchars functions to encode any user input that will be displayed on a webpage to prevent XSS attacks.
- Validate user input to ensure it conforms to expected formats, such as email addresses or phone numbers.
- Filter input to prevent unexpected data types, such as converting string inputs to integers when appropriate.
- Limit the types of HTML tags that are allowed and sanitize any input that will be displayed as HTML to prevent HTML injection attacks.
Here is some sample PHP code that demonstrates these techniques:
// Retrieve user input
$username = $_POST['username'];
$password = $_POST['password'];
$gender = $_POST['gender'];
// Validate input
if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
die('Invalid email address');
}
if (!ctype_alnum($password)) {
die('Invalid password');
}
if (!in_array($gender, array('male', 'female'))) {
die('Invalid gender');
}
// Sanitize input for database queries
$username = mysqli_real_escape_string($connection, $username);
$password = password_hash($password, PASSWORD_DEFAULT);
// Sanitize input for display as HTML
$username = htmlentities($username);
Note that this code is just a starting point and should be customized to fit the specific needs of your application.