Skip to content
PHP Logo

What best practices should be followed when implementing a confirmation code step for unsubscribing from a newsletter in PHP?

When implementing a confirmation code step for unsubscribing from a newsletter in PHP, it is important to generate a unique code for each unsubscribe request to ensure security and prevent unauthorized unsubscribes. This code should be included in the unsubscribe link sent to the user's email and validated upon clicking the link to confirm the unsubscribe action.

php
// Generate a unique confirmation code
$confirmation_code = md5(uniqid(rand(), true));

// Save the confirmation code in the database along with the user's email
// Send the unsubscribe link with the confirmation code to the user's email

// Validate the confirmation code when the user clicks the unsubscribe link
if(isset($_GET['code'])) {
    $code = $_GET['code'];
    
    // Retrieve the confirmation code from the database based on the user's email
    // Compare the retrieved code with the code from the unsubscribe link
    if($code === $confirmation_code_from_database) {
        // Unsubscribe the user from the newsletter
        // Update the database to reflect the user's unsubscribed status
        echo "You have successfully unsubscribed from the newsletter.";
    } else {
        echo "Invalid confirmation code.";
    }
}