What are the differences between htmlspecialchars(), htmlentities(), and addslashes() in PHP?

When dealing with user input in PHP, it is important to properly sanitize and escape the data to prevent security vulnerabilities such as cross-site scripting (XSS) attacks. Three common functions used for this purpose are htmlspecialchars(), htmlentities(), and addslashes(). htmlspecialchars() is used to convert special characters to HTML entities, htmlentities() converts all applicable characters to HTML entities, and addslashes() adds slashes before characters that need to be escaped in SQL queries. It is important to choose the appropriate function based on the context in which the data will be used.

// Example of using htmlspecialchars() to sanitize user input
$user_input = "<script>alert('XSS attack');</script>";
$sanitized_input = htmlspecialchars($user_input);
echo $sanitized_input;