What are the best practices for ensuring consistent handling of special characters in PHP forms?

Special characters in PHP forms can cause issues such as SQL injection attacks or unexpected behavior. To ensure consistent handling of special characters, it is important to sanitize input data using functions like htmlspecialchars() or mysqli_real_escape_string(). Additionally, setting the proper character encoding for your form can help prevent issues with special characters.

// Sanitize input data using htmlspecialchars()
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);

// Set character encoding
header('Content-Type: text/html; charset=UTF-8');

// Use mysqli_real_escape_string() for database queries
$stmt = $mysqli->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
$stmt->execute();
$stmt->close();