Handling PHP Session data

From SocialStrap Wiki
Jump to: navigation, search

Session handling

Sessions in PHP are used to preserve user's runtime data across subsequent accesses.

SocialStrap can handle PHP sessions in three different ways:

  • using traditional file handler like in any other php script
  • using database-driven session handler
  • using database-driven session handler with a separate, dedicated session database

Configuration option for this is under:

Settings -> General -> Session lifetime (Remember me) time in seconds. Set to 0 to use php server settings.

If you set this option to 0 (zero) then session is handled and configured and managed by the php server itself.

If the value is greater than zero then session is handled using database adapter.

If you want to set dedicated session database (v5.0+) you must add additional db adapter inside config.php file:

define('DB_SESSION_ADAPTER', 'PDO_MYSQL');
define('DB_SESSION_HOST', '181.4.54.110');
define('DB_SESSION_DATABASENAME', 'socialstrap');
define('DB_SESSION_USERNAME', 'username_here');
define('DB_SESSION_PASSOWRD', 'password_here');


If your session database becomes too large you can split the load between two or more databases using some of the user constants (IP address region, browser type etc.) to balance the session workload.


Getting Session data for external scripts

If you want to integrate SocialStrap with 3rd party scripts this is how you can retrieve session data from the database:

<?php

session_start();
$session_id = session_id();

if (!empty($session_id)) {

	$db = new yourDBAdapter();
	
	$result = $db->fetchRow("
		SELECT data
		FROM sessions
		WHERE id = '" . $db->escape($session_id) . "'
	");
	
	// sample data
	//$result['data'] = 'Default|a:2:{s:8:"language";s:2:"en";s:11:"pass_params";b:0;}Zend_Auth|a:1:{s:7:"storage";O:8:"stdClass":16:{s:2:"id";s:5:"93444";s:4:"type";s:4:"user";s:4:"name";s:4:"zico";s:11:"screen_name";s:4:"zico";s:5:"owner";s:1:"0";s:8:"password";s:60:"$2a$08$HNDylOI4WEBcumPnk2KxBOJFOh8LtMSFJFfejomJPH864bNkJ3bWC";s:8:"language";s:2:"en";s:4:"role";s:4:"user";s:5:"email";s:16:"zico@example.com";s:13:"activationkey";s:9:"activated";s:6:"avatar";s:44:"9aa32b523b591d36f69ca2fa6591740153babc34.png";s:5:"cover";s:13:"default/1.jpg";s:15:"relogin_request";s:1:"0";s:15:"default_privacy";s:8:"everyone";s:15:"profile_privacy";s:8:"everyone";s:9:"is_hidden";s:1:"0";}}';

	if (isset($result['data']))	{
	
		// decode serialized session and populate the $_SESSION superglobal with the result
		session_decode($result['data']);
		
		$user_id = $_SESSION['Zend_Auth']['storage']->id;
		$user_email = $_SESSION['Zend_Auth']['storage']->email;

	}

}

session_destroy();
die;