What best practices should be followed when creating a form that interacts with a PHP script?

When creating a form that interacts with a PHP script, it is important to properly sanitize and validate user input to prevent security vulnerabilities such as SQL injection and cross-site scripting attacks. Additionally, use POST method for sensitive data and implement CSRF protection to prevent unauthorized form submissions.

<?php

// Sanitize and validate user input
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

// Use POST method for sensitive data
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Process form data
}

// Implement CSRF protection
if(!empty($_POST['token']) && hash_equals($_SESSION['token'], $_POST['token'])) {
    // Form submission is valid
}

?>