Gehe zu deutscher Webseite

ViaThinkSoft CodeLib

This article is in:
CodeLibProgramming aidsPHP

functions.inc.php

<?php

define
('SIGNED_FORMDATA_SECRET''(place secret here)');

function 
get_signed_fieldname($fieldname) {
        return 
'signed_'.bin2hex($fieldname).'_'.hash_hmac('sha256'$fieldnameSIGNED_FORMDATA_SECRET);
}

function 
get_signed_formdata() {
        
$out = array();
        foreach (
$_REQUEST as $name => $value) {
                list(
$head$enc_fieldname$hash) = array_pad(explode('_'$name3), 3null);
                if (
$head != 'signed') continue;
                
$fieldname hex2bin($enc_fieldname);
                
$expect_hash hash_hmac('sha256'$fieldnameSIGNED_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