Read more about this type of attacks in wikipedia.

In short, we want to ensure that the form data is coming from our website.

We start by generating a token for the hidden field of the HTML form. Then we will validate the submitted form token against the token that we've set in the session.


Code:
<?php
session_start
();
session_regenerate_id(true);

if (isset(
$_POST['submit'])) {

    if (isset(
$_SESSION['token']) && ($_POST['token'] == $_SESSION['token'])) {
        
//token is ok, process data
    
}

}

$token hash('sha256'uniqid(mt_rand(), true));
$_SESSION['token'] = $token;

?>
HTML Code:
    <form method="POST" action="page.php">
        <input type="hidden" name="token" value="<?php echo $token; ?>">
        username: <input type="text" name="username">
        password: <input type="password" name="password" >
        <input type="submit" name="submit">
    </form>