What are the best practices for setting and handling variables in PHP based on user input from a form?

When setting and handling variables in PHP based on user input from a form, it is important to sanitize and validate the input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. One way to achieve this is by using PHP's filter_input() function to filter and validate the input data before assigning it to variables. Additionally, it is recommended to use prepared statements when interacting with a database to further protect against SQL injection attacks.

// Sanitize and validate user input from a form
$user_input = filter_input(INPUT_POST, 'user_input', FILTER_SANITIZE_STRING);

// Check if the input is not empty
if(!empty($user_input)) {
    // Assign the sanitized input to a variable
    $sanitized_input = $user_input;

    // Use prepared statements to interact with the database
    $stmt = $pdo->prepare("INSERT INTO table_name (column_name) VALUES (:input)");
    $stmt->bindParam(':input', $sanitized_input);
    $stmt->execute();
}