You Are Here: Home » How-To » Programming

How To Use Cakephp Sessions In External PHP Script?

By Debjit on October 25th, 2012 

CakePHP is a fantastic framework that lets you build any website from grounds up and that too very quickly. Although CakePHP provides all the built-in functions required for various works on a website but at times it happens that you need to access some CakePHP elements from an external script.

CakePHP Sessions

CakePHP Sessions

For instance, in this article we will talk about how you can access the CakePHP sessions from an external PHP file. With this tip you can both read and write to the CakePHP sessions from an external PHP script (which is not a part of the CakePHP framework). Lets find out:

Step 1: Make a copy of the index.php file available in the app/webroot folder and rename it as session_start.php. Make sure you make a copy of theĀ  index.php file and then rename this new copy to session_start.php. Now open the file and find the following line:

if (isset($_GET['url']) && $_GET['url'] === 'favicon.ico') {

Now, you need to remove this line and everything that comes after this line as well. After which you need to add the following code snippet to the end:

if(App::import('Core','Session')) { 
 $session = new CakeSession(); 

Alternatively you can download the following file and place it in the app/webroot folder of CakePHP - session_start.php.

Step 2: Now include this file in your external PHP script via the PHP include function. And then you can set the sessions in PHP as you would do for normal sessions using the $_SESSION variable. Make sure you do not use the session_start() command and only include the session_start.php file instead of the session_start() command. Here is a code snippet:

$_SESSION['testsessioncake'] = "Hellow World!"; 

The assumption for above code is that both the session_start.php file and the external php script resides in the app/webroot folder.

Step 3: Now you can access this session from your CakePHP controllers or models using the regular CakePHP sessions method:

echo $this->Session->read('testsessioncake'); 

Please let us know if this tutorial worked for you. We develop projects on CakePHP and other PHP based frameworks. If you have any development requirements or bug busting needs, please let us know.


How To Use Cakephp Sessions In External PHP Script? was originally published on on October 25, 2012 - 11:37 am (Indian Standard Time)