If you are using CakePHP in conjunction with an existing PHP application, chances are you need to import the normal application’s session into cake.
- Create a file called session_import.php or something similar in your cake app/config directory with the following contents :
<?php
if (!defined('DS')) {
define('DS', DIRECTORY_SEPARATOR);
}
if (!defined('ROOT')) {
define('ROOT', dirname(dirname(dirname(__FILE__))));
}
if (!defined('APP_DIR')) {
define('APP_DIR', basename(dirname(dirname(__FILE__))));
}
if (!defined('CAKE_CORE_INCLUDE_PATH')) {
define('CAKE_CORE_INCLUDE_PATH', ROOT);
}
if (!defined('WEBROOT_DIR')) {
define('WEBROOT_DIR', basename(dirname(__FILE__)));
}
if (!defined('WWW_ROOT')) {
define('WWW_ROOT', dirname(__FILE__) . DS);
}
if (!defined('CORE_PATH')) {
if (function_exists('ini_set')) {
ini_set('include_path', ini_get('include_path') .
PATH_SEPARATOR .
CAKE_CORE_INCLUDE_PATH . PATH_SEPARATOR . ROOT . DS . APP_DIR . DS);
define('APP_PATH', null);
define('CORE_PATH', null);
} else {
define('APP_PATH', ROOT . DS . APP_DIR . DS);
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
}
include APP_PATH . 'config' .DS .'core.php';
include CAKE_CORE_INCLUDE_PATH .DS . 'cake' . DS . 'basics.php';
include CAKE_CORE_INCLUDE_PATH .DS . 'cake' . DS . 'config' . DS. 'paths.php';
include CAKE_CORE_INCLUDE_PATH .DS . 'cake' . DS . 'libs' . DS . 'object.php';
include CAKE_CORE_INCLUDE_PATH .DS . 'cake' . DS . 'libs' . DS . 'security.php';
include CAKE_CORE_INCLUDE_PATH .DS . 'cake' . DS . 'libs' . DS . 'session.php';
function init_framework($session) {
$s = new CakeSession(null);
$s = new CakeSession(null);
$s->renew();
// Basic authentication information
$s->write('User.id', $session['UserID']);
// Write whatever session information you want to share with Cake
}
?>
Set whatever session attributes you care about in the init_framework() function.
- Add the following to the end of your app/config/bootstrap.php file.
// Get the session from the original login
if(isset($_COOKIE[PHP_SESSION_ID])){
session_id($_COOKIE[PHP_SESSION_ID]);
}
session_start();
Where PHP_SESSION_ID is the session id string you are using for cookies.
- Somewhere in your existing application (the most sensible place is probably just you have authenticated the user’s login), include your new cake session_import.php script (in my case the cake application is in a sub-folder called ext ) and initialise your framework.
// Initialise the framework sessions
require_once $_SERVER['DOCUMENT_ROOT'] . '/ext/app/config/session_import.php';
init_framework($_SESSION);
Based on this post to the cake newsgroup - thanks to whoever posted it!