Ever wanted to set your own session id?
Well, I did. I was creating a webservice where authentication would be done with a ‘token’.
This token would simply be a random guid given to that user after he logged on with his username/password.
Now, this random guid/string would be the session ID.
That way, if the user does an action with that token, we can easily know who it is.
But enough with the ‘why I’ wanted to do it. You’re here for yourself right?, so you’ll be interested in some sample code.
In basic php you’d do it by giving the ID parameter to the session_id() method
//taken from php.net string session_id ([ string $id ] )
But how can we do this in CakePHP?
One possibility would be by implementing sessions ourself. But then why use a framework that all those nice components?
The session component has the ability to set the session id. This must be done in the beforefilter method of your controller.
Doing it later would be to late, as the session would already be started.
So in your controller you’d have something like this:
public $components = array('Session'); public function beforeFilter() { $sessionid = 'myownsessionid'; if($sessionid != null && $sessionid != '') { $this->Session->id($sessionid); } }
There you go
, it’s that easy!