how to generate an unsubscribe link for the newsletter?


I want to write a newsletter with php. but i have a question: how can i generate a code for unsubscribe. In fact i want a unique code for each subscriber. for example in '' you can see something like this:''. and another question is that this code should be saved in data base or no?(because i think if it's unique for each person, it's not necessary to generate every time whiling send newsletters). any idea?

Generate a hash of the user id + some secret string, put the id and the hash to the link, and serve it using a script which would unsubscribe the user, after verifying the hash.

The hash doesn't have to be in a database, just compute it on the fly.

Script creating the unsubscribe link:

$link = "unsubscribe.php?id=$user['id']&validation_hash=".md5($user['id'].$SECRET_STRING)
<a href="<?=$link?>">Unsubscribe</a>

Script processing the unsubscribe link:

function unsubscribe() {

    $expected = md5( $user['id'] . $SECRET_STRING );

    if( $_GET['validation_hash'] != $expected )
        throw new Exception("Validation failed.");

    sql("UPDATE users SET wants_newsletter = FALSE WHERE id = " . escape($_GET['id']);

It's not the most secure thing ever, but good enough.