ViaThinkSoft CodeLib
This article is in:
CodeLib → Programming aids → PHP
functions.inc.php
page1.php
target.php
<?php
define('SIGNED_FORMDATA_SECRET', '(place secret here)');
function get_signed_fieldname($fieldname) {
return 'signed_'.bin2hex($fieldname).'_'.hash_hmac('sha256', $fieldname, SIGNED_FORMDATA_SECRET);
}
function get_signed_formdata() {
$out = array();
foreach ($_REQUEST as $name => $value) {
list($head, $enc_fieldname, $hash) = array_pad(explode('_', $name, 3), 3, null);
if ($head != 'signed') continue;
$fieldname = hex2bin($enc_fieldname);
$expect_hash = hash_hmac('sha256', $fieldname, SIGNED_FORMDATA_SECRET);
if (hash_equals($expect_hash, $hash)) {
$out[$fieldname] = $value;
}
}
return $out;
}
page1.php
<?php
include 'functions.inc.php';
echo '<form method="POST" action="target.php">';
echo 'Signed Field1: <input type="text" name="'.get_signed_fieldname('field1').'" value="abc"><br>';
echo 'Signed Field2: <input type="text" name="'.get_signed_fieldname('field2').'" value="def"><br>';
echo 'Unsigned Field: <input type="text" name="field3" value="xyz"><br>';
echo '<input type="submit">';
echo '</form>';
target.php
<?php
include 'functions.inc.php';
print_r(get_signed_formdata());
// Example usage:
foreach (get_signed_formdata() as $name => $value) {
mysql_query("UPDATE users SET `$name` = '".mysql_real_escape_string($value)."' where id = ".$_SESSION['user_id']);
}
Daniel Marschall
ViaThinkSoft Co-Founder
ViaThinkSoft Co-Founder