Search code examples
phpwordpressencryptionemail-verification

Creating a unique verification code from a single number?


I am making a plugin that provides a form, letting anyone submit a post to my Wordpress site (custom post type). I am looking for a very basic means of deterring bots/spammers though, so I want to e-mail a confirmation code that they can click and change the status to Published.

I would prefer not to store anything in the database, so I was thinking of just sending something like "verification.php?id=12", where the ID is the post ID. That is pretty obvious though, so I would like to make that single number look more complex, then "decrypt" it when the link is clicked to reveal the actual Post ID.

Pseudo Code:

If ($_GET['veriID'] != '')
$lastchar = substr($_GET['veriID'], -1);
publish_post($lastchar);

What would be some options to achieve this? Should I just generate a random string and append the post ID to the end or is there a better method?


Solution

  • You can use HMAC to authenticate the request. The resulting url will look like the following:

    .../verification.php?post=12&hash=5f13532e49447facaa3dce9080bfffec3c6731eca6b4d590670dd0b1137e7476
    

    To generate the hash, the HMAC algorithm is used. This has the advantage that a secret value is used. Therefore the value cannot be computed by the message (the post id) alone.

    Code to generate the hash value:

    define('secret', 'really super secret value');
    
    $post_id = 12;
    
    // Get the hash
    echo hash_hmac('sha256', $post_id, secret);
    

    You can store the secret in a constant value or better: one per plugin-installation.

    Since you can always compute the hash from the post-id, no data needs to be stored in a database.