There are three functions involved. The first Init is run before the content is parsed. The second is parseContent where the content is generated. The third is displayPage that renders the page and HTML for the user.
They are within an OOP class that uses template files which have #KEYWORDS# that are dynamically replaced. session_start() is also in effect
Init()
$this->content = false;
$this->inputVerified = false;
if ( $this->input['token'] && $_SESSION['TOKEN'] && $this->input['token'] === $_SESSION['TOKEN'] )
{
$this->inputVerified = true;
unset( $_SESSION['TOKEN'] );
}
parseContent()
// content here
if ( $form_submission )
{
if ( $this->inputVerified )
{
// CSRF PROOF?
}
}
$this->content = 'DYNAMIC TEMPLATE CONTENT';
displayPage()
if ( strpos( $this->content, '#TOKEN#' ) )
{
$main = hash_hmac( 'sha512', mt_rand(), mt_rand() );
$_SESSION['TOKEN'] = $main;
$this->content = str_replace( '#TOKEN#', $main, $this->content );
}
What I like about this is I only had to do the following to implement it:
- Include a hidden
tokeninput field with the value of#TOKEN#on any sensitive formdisplayPage()will detect and replace this (with questionable efficiency)
- Check for
$this->inputVerifiedon any page that will process a sensitive formInit()will detecttokeninput and if it matches its$_SESSIONcounterpart will set$this->inputVerifiedtotrueonly on the first valid submission,falseif refreshed or otherwise.
Is it enough?
$_SESSION-$tokencomparison. Maybe set the HTML token to the hash data and$_SESSIONto the final hash salted with the IP, that way the submitted token salted with the current IP must be equal to the original token salted with the original IP? \$\endgroup\$