Cookie-less REST API with Laravel

We learned to rely on browser cookies for many years. Some of us don’t even realize and understand the “magical” relationship between a browser and PHP script on server-side. Only when we get out of the “box” and look at what is going on, then we start to grasp the oddities.

When we work on a mobile application or a desktop application, which does not use any embedded browser or such components, we have to do think differently and come up with another way to associate separate requests with same PHP “session” (if you want to call them).

With Laravel 3, it was a bit of a headache to alter the way the sessions were started and loaded. We had to bodge it so that if the request contains a special HTTP header, which carries an authentication token, then we use that token/ID to load the session: pretty neat.

Header entry:

X-MY-COMPANY-AUTH-TOKEN: a-random-string

PHP code in application/start.php

// * * *
if ( ! Request::cli() and Config::get('session.driver') !== ''){
    $headers = getallheaders();
    $id = null;
    if (isset($headers['X-MY-COMPANY-AUTH-TOKEN'])) {
        $id = $headers['X-MY-COMPANY-AUTH-TOKEN'];
    Session::load($id);//we have modified this static function as well

PHP code on laravel/session.php

 * Create the session payload and load the session.
 * @param string $id Optional parameter added for COOKIE-less communication
 * @return void
public static function load($id = null)

    //refactored to allow COOKIE-LESS communication
    if (empty($id)) {//this does not break communication via browser
        $name = Config::get('session.cookie');//e.g. 'laravel_session';
        $id   = Cookie::get($name);//session ID

However, it is annoying that many developers/companies still don’t take it seriously when it comes to cookie-less communication and user privacy. I think, they do want to track every move of their visitors/users!

Leave a Reply