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

When handling form actions in PHP scripts, it is important to validate user input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. Additionally, it is best practice to use prepared statements when interacting with a database to protect against SQL injection. Finally, always sanitize and validate user input before processing it to ensure data integrity.

// Example of handling form actions in PHP script

// Validate user input
if(isset($_POST['submit'])){
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Sanitize and validate user input
    $username = filter_var($username, FILTER_SANITIZE_STRING);
    $password = filter_var($password, FILTER_SANITIZE_STRING);

    // Use prepared statements to interact with database
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
    $stmt->bindParam(':username', $username);
    $stmt->bindParam(':password', $password);
    $stmt->execute();

    // Process user input
    if($stmt->rowCount() > 0){
        // User authentication successful
        echo "Login successful!";
    } else {
        // User authentication failed
        echo "Invalid username or password";
    }
}