session_start( );
$username = htmlentities($_SESSION['username']);
print "Hello $username.";
In this case, if you don't call
session_start( ), $_SESSION
isn't set.
Be sure to secure the server and location where your session files
are located (the filesystem, database, etc.); otherwise your system
will be vulnerable to identity spoofing.
Example 9-3. pc_decode( )
function pc_decode($data, $hash) {
if (!empty($data) && !empty($hash)) {
if (md5($GLOBALS['secret'] . $data) == $hash) {
return unserialize($data);
} else {
error_log("Validation Error: Data has been modified");
return false;
}
}
return false;
}
The pc_decode( ) function recreates the hash of
the secret word and compares it to the hash value from the form. If
they're equal, $data is valid, so
it's unserialized. If it flunks the test, the
function writes a message to the error log and returns
false.
These functions go together like this:
<?php
$secret = 'Foo25bAr52baZ';
// Load in and validate old data
if (! $data = pc_decode($_GET['data'], $_GET['hash'])) {
// crack attempt
}
// Process form (new form data is in $_GET)
// Update $data
$data['username'] = $_GET['username'];
$data['stage']++;
unset($data['password']);
// Encode results
list ($data, $hash) = pc_encode($data);
// Store data and hash inside the form
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
...
<input type="hidden" name="data"
value="<?php echo htmlentities($data); ?>">
<input type="hidden" name="hash"
value="<?php echo htmlentities($hash); ?>">
</form>
At the top of the script, we pass pc_decode( ) the
variables from the form for decoding. Once the information is loaded
into $data, form processing can proceed by
checking in $_GET for new variables and in
$data for old ones. Once that's
complete, update $data to hold the new values and
then encode it, calculating a new hash in the process. Finally, print
out the new form and include $data and
$hash as hidden variables.