Sessions

Brain offers a session class for database sessions, and made primarily for use with Brain’s Auth. While you can add, view, and remove data from the session, it’s primary goal is to keep user authentication as secure as possible. This doesn’t happen with cookie based sessions unless you track the session ID in the database, and if you’re going to do that, then why not use database sessions?

The session class analyzes the current URI scheme and cookie_secure setting to determine if it should set a cookie for SSL encrypted requests, or another for non-SSL encrypted requests. Again, with security at the focus of the class, we want to ensure that cookies used for SSL encrypted requests are not available for non-SSL encrypted requests. You can force the sessions class to use a single cookie, and let it be available everywhere, but please do this at your own risk.

All session data is encrypted. All session IDs stored in the cookies are encrypted. Even if a person can view the contents of the cookie, there is not much of a chance they could alter it in a meaningful way.

Multiple sessions can be attached to an Auth user. By default this is turned off, but if you turn it on your user will be able to log in from multiple devices. Provided that you allow for persistent cookies, or have set their expiration out pretty far in the future, your users will enjoy a secure session.

Configuration

General session configuration is done in config/session.php. There you are able to set the session expiration, cookie params, refresh rate, and more. Any class property can be set here. Have a look at the top of Session.php to see what damage you can do!

// Set config in config/session.php
$cfg['session_config'] = [
  // 12 Mins (set to zero to drop @ browser close, FALSE for long range persistent session)
  'secs_expire'            => 720,
  // Force IPs to match or no?
  'enforce_ip_match'       => FALSE,
  // Force user agent match or no?
  'enforce_ua_match'       => TRUE,
  // Cookie secure or not?
  'cookie_secure'          => TRUE,
  // Multiple user sessions?
  'multiple_user_sessions' => TRUE,
  // How often should the session be regenerated?
  'session_refresh'        => 180
];

Usage

// Get the session instance to work with
$session = $this->container['session'];

// Add something to the session
$session->set_sessdata('something', 'nice');

// Get something from the session
$value = $session->sessdata('something');

// Add a flash token
$session->set_flashdata('dummy', 'yup');

// Get the value of the flash token
$value = $session->flashdata('dummy');

// Keep flash data for another request
$session->keep_flashdata('dummy');

// Kill the session
$session->sess_destroy();

Router

Brain’s routing is similar to CodeIgniter’s in that the first URI segment is the controller, any second URI segment is a method other than index, and any additional URI segments are method arguments. Routes can also be configured in config/routes.php to swap route for route. The default route is also defined in config/routes.php.

Router::load_controller()

Once the router class has determined which controller and method to call, it passes that information to the load_controller method. This method calls the requested controller and method. The beauty here is that after a controller and method are called, the load_controller method can be called again if necessary. So for instance, if you have a situation where you might do an internal redirect, you could instead just use load_controller to load up the controller and method you wish. This is really nice if there is session, cookie, or post data, because there is no need to recycle the data.

Dirs for Controllers

As configured in config/core.php, Brain will first attempt to find your controller in APPPATH . ‘controllers/’, and if the controller isn’t found, it will look in BRAIN . ‘controllers/’. You can add more dirs for controllers if you wish, simply use the add_path method, and supply a full path to the location.

Routing Config

Besides standard text matching for custom routes, Brain offers full regex matching of routes. Mod rewrite may be preferred for complex URL rewriting, but if the key of your routing rule is regex, the value associated with the key is used directly. In most cases you may want to route to a method in the controller where the URI segments can be analyzed, then call another method of further action.

Pagination

Brain’s Pagination class can paginate via URI segment or query string. The only real difference is the configuration.

URI Segment Based Pagination

$p = $this->container['pagination.standard'];

$links = $p->create_links();

Query String Based Pagination

$p = $this->container['pagination.query_string'];

$links = $p->create_links();

In either case the configuration was obtained from the pagination config file. Overall configuation and usage should be similar to CodeIgniter.

Model

Brain now uses Doctrine DBAL for database interaction, and models are typically where all of the queries will live. Load a model anywhere and use it easily:

Loading & Using Models

// Load the model with filename example_model.php
$example = Model::load('example_model');

// Call a method named "get_stuff" from the example model
$stuff = $example->get_stuff('cool');

All models should extend BaseModel, which allows for easy DBAL usage via $this->db.

use \Brain\Lib\Container;

use \App\Lib\BaseModel;
use \Brain\Lib\Container;

class Example_model extends BaseModel {

	public function __construct( Container $container )
	{
		parent::__construct( $container );
	}

	public function get_stuff( $type )
	{
		$sql = '
			SELECT * 
			FROM stuff 
			WHERE type = :type';

		$stmt = $this->db->executeQuery( $sql,
			[ 'type' => $type ]
		);

		if( $rows = $stmt->fetchAll() )
		{
			return $rows;
		}

		return NULL;
	}
}

Log

For logging or debugging, the Log class allows for writing data to a file or Firebug console by way of FirePHP.

Mode

The mode is either off, file, or fb. The value is set in the container, but you can override it manually using the public mode method.

Write

// Log the string 'asdf'
Log::write('asdf');

If the log mode is file, unless a path is specified as the second parameter, the file is created/written at
the logs directory set in the container, with a filename of log-<today’s date>.php.

License

Brain is a compilation of code with sources that have both proprietary licensing and licensing that conflicts with free distribution of the framework. Brain is not available for download. Should licensing issues be cleared up in the future, Brain will be licensed under MIT or BSD licensing. It’s the right thing to do.

Input

Based on CodeIgniter’s Input class, Brain’s Input class usage is very similar. Using the input class allows for some automatic and manual input filtering.

Automatic Input Filtering

As long as you use the Input class to access $_POST, $_GET, and $_COOKIE data, you will be accessing data that has:

  • Clean array keys
  • Values run through utf8_clean_string
  • Values run through remove_invisible_characters
  • Newlines in values standardized

utf8_clean_string

By using iconv (if available), characters are converted to UTF-8, and if they can’t be represented in UTF-8, they are discarded.

remove_invisible_characters

This prevents sandwiching null characters between ascii characters, like Java\0script.

Access to $_GET

// Retrieve $_GET['key_name']
$val = Input::get('key_name');

// Retrieve $_GET['key_name'] and run through XSS clean
$val = Input::get('key_name', TRUE);

Access to $_POST

// Retrieve $_POST['key_name']
$val = Input::post('key_name');

// Retrieve $_POST['key_name'] and run through XSS clean
$val = Input::post('key_name', TRUE);

Access to $_COOKIE

// Retrieve $_COOKIE['key_name']
$val = Input::cookie('key_name');

// Retrieve $_COOKIE['key_name'] and run through XSS clean
$val = Input::cookie('key_name', TRUE);

Access to $_SERVER

// Retrieve $_SERVER['key_name']
$val = Input::server('key_name');

// Retrieve $_SERVER['key_name'] and run through XSS clean
$val = Input::server('key_name', TRUE);

Access to IP Address

$ip = Input::ip_addr();

Access to User Agent

$ua = Input::user_agent();

Determine if Ajax Request

$bool = Input::is_ajax_request();

Determine if CLI Request

$bool = Input::is_cli_request();

XSS Clean

$cleaned_value = Input::xss_clean( $original_value, $is_image = FALSE );