What are some best practices for handling form submissions in PHP to avoid unwanted behavior?

When handling form submissions in PHP, it is important to validate and sanitize user input to prevent unwanted behavior such as SQL injection or cross-site scripting attacks. One best practice is to use prepared statements when interacting with a database to prevent SQL injection. Additionally, always sanitize user input using functions like htmlspecialchars() or filter_var() to prevent cross-site scripting attacks.

// Example of handling form submission with validation and sanitization

// Validate and sanitize form input
$name = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : '';
$email = isset($_POST['email']) ? filter_var($_POST['email'], FILTER_SANITIZE_EMAIL) : '';
$message = isset($_POST['message']) ? htmlspecialchars($_POST['message']) : '';

// Use prepared statements to interact with the database
$stmt = $pdo->prepare("INSERT INTO messages (name, email, message) VALUES (?, ?, ?)");
$stmt->execute([$name, $email, $message]);

// Redirect after form submission
header("Location: thank-you.php");
exit;