14.3. Verifying Data with Hashes

Problem

You want to make sure users don’t alter data you’ve sent them in a cookie or form element.

Solution

Along with the data, send an MD5 hash of the data with a secret word. When you receive the data back, compute the hash of the received value with the same secret word. If they don’t match, the user has altered the data.

Here’s how to print a hash in a hidden form field:

$secret_word = 'flyingturtle';
$id = 2836;
$hash = md5($secret_word . $id);

print<<<_HTML_
<input type="hidden" name="id" value="$id">
<input type="hidden" name="idhash" value="$hash">
_HTML_;

Here’s how to verify the hidden form field data when it’s submitted:

$secret_word = 'flyingturtle';

if (md5($secret_word . $_REQUEST['id']) == $_REQUEST['idhash']) {
    $id = $_REQUEST['id'];
} else {
    die("Invalid data in $_REQUEST[id]");
}

Discussion

When processing the submitted form data, compute the hash of the submitted value of $_REQUEST['id'] and the secret word. If it matches the submitted hash, the value of $_REQUEST['id'] has not been altered by the user. If the hashes don’t match, you know that the value of $_REQUEST['id'] you received is not the same as the one you sent.

To use a verification hash with a cookie, add the hash to the cookie value with join( ) :

$secret_word = 'flyingturtle';
$cookie_value = 'Ellen';
$hash = md5($secret_word . $cooki_value);

setcookie('name',join('|',array($cookie_value,$hash)));

Parse the hash from the cookie value with explode( ) :

$secret_word ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.