I use this class (taken from the blog tutorial) to generate unique keys for validating the form:
class formKey {
private $formKey;
private $old_formKey;
function __construct() {
if(isset($_SESSION['form_key'])) {
$this->old_formKey = $_SESSION['form_key'];
}
}
private function generateKey() {
$ip = $_SERVER['REMOTE_ADDR'];
$uniqid = uniqid(mt_rand(), true);
return md5($ip . $uniqid);
}
public function outputKey() {
$this->formKey = $this->generateKey();
$_SESSION['form_key'] = $this->formKey;
return $this->formKey;
}
public function validate() {
if($_POST['form_key'] == $this->old_formKey) {
return true;
}
else {
return false;
}
}
}
Everything on my site first goes through index.php, so I put this in index.php: $formKey = new formKey();
Then in each form I put this: <?php $formKey->outputKey();?> <?php $formKey->outputKey();?>
This generates this: <input type="hidden" name="form_key" id="form_key" value="7bd8496ea1518e1850c24cf2de8ded23"/>
Then I can just check if(!isset($_POST['form_key']) || !$formKey->validate())
I have two problems. First: I cannot use more than one form per page, because only the last generated key will be checked.
Second: since everything goes through index.php first, if I use ajax to validate the form, the first time it will be checked, and the second not, because index.php generates a new key, but the pages containing the form are not updated, so the form key not updated..
, .. , / /, ?? !!!