What are the best practices for handling string variables in PHP?

When handling string variables in PHP, it's important to sanitize user input to prevent SQL injection and other security vulnerabilities. Use functions like htmlspecialchars() to escape special characters and htmlentities() to convert characters to HTML entities. Additionally, always validate and sanitize input before using it in database queries or displaying it on a webpage.

// Sanitize user input using htmlspecialchars()
$userInput = "<script>alert('XSS attack');</script>";
$sanitizedInput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');

// Validate and sanitize input before using it in a database query
$unsafeInput = $_POST['user_input'];
$cleanInput = filter_var($unsafeInput, FILTER_SANITIZE_STRING);

// Display sanitized input on a webpage
echo htmlentities($cleanInput);