Skip to content

Instantly share code, notes, and snippets.

@zacscott
Last active December 30, 2015 04:49
Show Gist options
  • Save zacscott/7778663 to your computer and use it in GitHub Desktop.
Save zacscott/7778663 to your computer and use it in GitHub Desktop.
Utility to prevent cross-site request forgeries (XSRF).
<?php
namespace net\zeddev\util;
// start session if not already
if (session_id() == '')
session_start();
/**
* Utility to prevent cross-site request forgeries (XSRF) using a request scoped
* token/nonce/one-time key.
*
* @author Zachary Scott <zscott.dev@gmail.com>
*/
class XSRFToken {
private $name; // the token name in the session
private $token; // the token value
public function __construct($name = '') {
$this->name= "__xsrftok$name";
// get token from session
if (isset($_SESSION[$this->name]))
$this->token = $_SESSION[$this->name];
}
// generates a new, random token
private function gentoken() {
$this->token = $_SESSION[$this->name] = uniqid('', true);
}
/** Checks the token from the client request. */
public function check() {
return isset($_REQUEST[$this->name])
&& $_REQUEST[$this->name] == $this->token;
}
/**
* Builds & outputs a hidden form <input> which contains the token data.
* should be embedded in the containing <form>.
*/
public function put() {
// first generate a new token
$this->gentoken();
$style = 'style="display:none;"';
$name = 'name="'. $this->name .'"';
$token = 'value="'. $this->token .'"';
echo "<input type=\"hidden\" $style $name $token />\n";
}
}
?>
<?php
require_once dirname(__FILE__).'/code/class.XSRFToken.php';
$token = new \net\zeddev\util\XSRFToken();
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>XSRFToken Test</h1>
<?php
// check the form token
if (isset($_GET['TokenForm'])) {
if ($token->check()) {
echo "<p>Token check passed</p> \n";
} else {
echo "<p>Token check failed</p> \n";
}
}
?>
<form action="token.php" method="get">
<label for="name">Your name:</label>
<input type="text" name="name"/>
<?php $token->put() ?>
<input type="submit" value="Submit" name="TokenForm"/>
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment