What are the best practices for handling form actions and methods in PHP?

When handling form actions and methods in PHP, it is important to properly validate and sanitize user input to prevent security vulnerabilities such as SQL injection and cross-site scripting attacks. Additionally, using POST method for sensitive data and GET method for non-sensitive data is a good practice to enhance security. Lastly, always use prepared statements when interacting with a database to prevent SQL injection attacks.

// Example of handling form actions and methods in PHP

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // Sanitize and validate user input
    $username = filter_var($_POST["username"], FILTER_SANITIZE_STRING);
    $password = filter_var($_POST["password"], FILTER_SANITIZE_STRING);
    
    // Use prepared statements to interact with the database
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
    $stmt->bindParam(':username', $username);
    $stmt->bindParam(':password', $password);
    $stmt->execute();
    
    // Process the form data
    if ($stmt->rowCount() > 0) {
        // User authentication successful
    } else {
        // User authentication failed
    }
}