Are there any best practices for handling form actions in PHP popups?

When handling form actions in PHP popups, it is important to ensure that the form data is properly sanitized and validated to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. Additionally, the form submission should be processed securely and any error messages should be displayed to the user in a clear and user-friendly manner.

<?php
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize and validate form data
    $input_data = filter_input_array(INPUT_POST, [
        'username' => FILTER_SANITIZE_STRING,
        'password' => FILTER_SANITIZE_STRING
    ]);

    // Process form submission
    if (!empty($input_data['username']) && !empty($input_data['password'])) {
        // Perform necessary actions with the form data
        // For example, authenticate user or save data to database
        
        // Redirect or display success message
        echo "Form submitted successfully!";
    } else {
        // Display error message if form data is invalid
        echo "Please fill in all required fields.";
    }
}
?>