How can PHP developers handle email validation and activation links for user registration effectively and securely?

To handle email validation and activation links for user registration effectively and securely, PHP developers can generate a unique activation token for each user during registration, store it securely in the database, and send it via email to the user. When the user clicks on the activation link, the token should be validated to ensure it matches the one stored in the database, and the user's account can then be activated.

// Generate a unique activation token
$activation_token = bin2hex(random_bytes(16));

// Store the activation token in the database
// Assume $db is the database connection
$stmt = $db->prepare("INSERT INTO users (email, activation_token) VALUES (?, ?)");
$stmt->bind_param("ss", $email, $activation_token);
$stmt->execute();

// Send the activation email to the user
$to = $email;
$subject = 'Account Activation';
$message = 'Click on the following link to activate your account: http://example.com/activate.php?token=' . $activation_token;
$headers = 'From: webmaster@example.com';
mail($to, $subject, $message, $headers);

// Validate the activation token when the user clicks on the link
$token = $_GET['token'];
$stmt = $db->prepare("SELECT * FROM users WHERE activation_token = ?");
$stmt->bind_param("s", $token);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows == 1) {
    // Activate the user's account
    $row = $result->fetch_assoc();
    $user_id = $row['id'];
    $stmt = $db->prepare("UPDATE users SET activated = 1 WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    echo 'Account activated successfully!';
} else {
    echo 'Invalid activation token!';
}