Tags
Asked 2 years ago
9 Jun 2021
Views 208
ajamil

ajamil posted

PHP Sanitize Data

PHP Sanitize Data
jaggy

jaggy
answered Apr 26 '23 00:00

Sanitizing data in PHP is important to prevent various types of attacks, such as SQL injection, XSS (cross-site scripting), and other types of malicious input. Here are some ways to sanitize data in PHP:

Use filter_input() function: The filter_input() function is used to get external variables, such as POST, GET, and COOKIE, and apply a filter to the input. It can filter and validate data based on various types, such as string, integer, boolean, and more.
Example:


$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);

Use filter_var() function: The filter_var() function is used to filter a single variable with a specified filter. It can filter and validate data based on various types, such as email, URL, IP address, and more.
Example:



$email = "example@example.com";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo("$email is not a valid email address");
}

Use htmlentities() function: The htmlentities() function converts characters to their corresponding HTML entities. This function can be used to prevent XSS attacks by converting special characters to their HTML entities.
Example:



$name = htmlentities($_POST['name']);

Use mysqli_real_escape_string() function: The mysqli_real_escape_string() function is used to escape special characters in a string for use in an SQL statement. This can help prevent SQL injection attacks.
Example:


$username = mysqli_real_escape_string($connection, $_POST['username']);

Note that these are just some examples of how to sanitize data in PHP. It's important to use a combination of these methods, depending on the specific use case, to ensure that your code is secure.
Post Answer