These classes are based on a (slightly) improved set of classes and functions that were originally built on CodeAcademy and that we have found extremely useful. They can serve as a basis for not only UserSpice or for your project as a whole. If you copy and paste this code, please get rid of the space before the opening php tag.

Usage

We use a special Token system to prevent Cross Site Request Attack Forgery on your forms. This is a two step process.

Step 1: Add this check to your $_POST submission:

$token = $_POST['csrf'];
if(!Token::check($token)){
die('Token doesn\'t match!');
}

Step 2: Add this “hidden field” to your form before the submit button
If the form is in html, add this:
(remove the @ symbol)

<@input type="hidden" name="csrf" value="
(For users of older versions of UserCake/UserSpice)
";
?>

(remove the @ symbol)

<@input name="csrf" type="hidden" value=""<?=Token::generate();?" />" >

Session.php

<?php
class Session {

	public static function exists($name){
		return (isset($_SESSION[$name])) ? true : false;
	}

	public static function put($name, $value){
		return $_SESSION[$name] = $value;
	}

	public static function delete($name){
		if (self::exists($name)) {
			unset($_SESSION[$name]);
		}
	}

	public static function get($name){
		return $_SESSION[$name];
	}

	public static function flash($name, $string = ''){
		if (self::exists($name)) {
			$session =  self::get($name);
			self::delete($name);
			return $session;
		} else{
			self::put($name, $string);
		}
	}

	public static function uagent_no_version(){
		$uagent = $_SERVER['HTTP_USER_AGENT'];
		$regx = '/\/[a-zA-Z0-9.]+/';
		$newString = preg_replace($regx,'',$uagent);
		return $newString;
	}

}

Token.php

<?php
class Token {
	public static function generate(){
		return Session::put(Config::get('session/token_name'), md5(uniqid()));
	}

	public static function check($token){
		$tokenName = Config::get('session/token_name');

		if (Session::exists($tokenName) && $token === Session::get($tokenName)) {
			Session::delete($tokenName);
			return true;
		}
		return false;
	}
}