Assign and read session of user by PHPSESSID read from cookie

4.3k views Asked by At

I want to authenticate chat user in my php app (through websockets). Now I am sending with chat message all cookies from domain. One of these cookies is session id. Is there any option to do something like this:

session_id($cookies['PHPSESSID']);
session_start();
echo $_SESSION['user']['username']; 

Or maybe is there any other method to authenticate user ?

1

There are 1 answers

2
Lasse On

Yes, you can do that, with one small adjustment:

session_id($_COOKIE['PHPSESSID']); //We use the `$_COOKIE` global array to access cookies
session_start();
echo $_SESSION['user']['username']; 

Be careful, though. Since you're using the same cookie as PHP ifself, this value is auto-generated unless of course you use session_id($_COOKIE['PHPSESSID']); before-hand. You'll need to make sure that an automatic session id is generated the first time the user visits your site.