PHP - How to escape strings

  • Last updated: Oct 13, 2024
  • Views: 12
  • Author: Admin
PHP - How to escape strings

Hello colleagues.

In today's article, we will talk about how you can escape strings in the PHP programming language.

String escaping in PHP is done to prevent security issues and preserve your data when working with databases or displaying information on web pages. Today we will show you three simple functions that will help you with this.

 

  1. addslashes() function.
  2. mysqli_real_escape_string() function.
  3. htmlspecialchars() function.

 

1. Function addslashes().

The addslashes() function adds a backslash in front of characters that may affect string processing, such as single quotes ('), double quotes ("), and backslashes (). addslashes ensures that data is stored correctly when using string values ​​in SQL queries or insert into HTML code.

Example:

$string = "It's a simple number.";
$string = addslashes($string);
echo $string;

Result:

It\'s a simple number.

 

2. Function mysqli_real_escape_string().

If you are using MySQLi, then you can use the mysqli_real_escape_string() built-in function to escape strings before inserting them into SQL queries. This feature automatically handles special characters that might cause requests to be processed incorrectly.

Example:

$string = "It's a simple number.";
$string = mysqli_real_escape_string($connection, $string);
echo $string;

Result:

It\'s a simple number.

 

3. Function htmlspecialchars().

The htmlspecialchars() function is used to escape special characters in HTML code. htmlspecialchars() converts characters such as <, >, &, ", ' into their respective HTML entities to prevent unwanted code from executing or display corruption on web pages.

Example:

$string = "<script>alert('XSS');</script>";
$string = htmlspecialchars($string);
echo $string;

 

Thank you all, I hope my article was of some help to you.

 

SIMILAR ARTICLES