What are best practices for handling user authentication and registration processes in PHP, including sending activation emails and using security tokens?

When handling user authentication and registration processes in PHP, it is important to ensure secure practices such as using password hashing, sending activation emails for account verification, and utilizing security tokens to prevent CSRF attacks. Below is an example of how to implement these best practices in PHP:

// User registration process
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$activation_token = bin2hex(random_bytes(16));

// Save user data to database with hashed password and activation token

// Send activation email
$to = $_POST['email'];
$subject = 'Activate your account';
$message = 'Click the following link to activate your account: http://example.com/activate.php?token=' . $activation_token;
$headers = 'From: admin@example.com';
mail($to, $subject, $message, $headers);

// User authentication process
if (password_verify($_POST['password'], $hashed_password)) {
    // Login successful
    // Generate and store security token
    $security_token = bin2hex(random_bytes(32));
    $_SESSION['security_token'] = $security_token;
} else {
    // Login failed
}

// Validate security token on each authenticated request
if ($_SESSION['security_token'] !== $_POST['security_token']) {
    // Invalid security token, deny access
    exit('Invalid security token');
}