Jacob
Jacob

Reputation: 461

How to get started with session id's in PHP and MySQL?

So I recently made the decision to use Session ID's for authentication on my website instead of JWT's, so I'm still trying to play catch up a little bit here.

I guess my concern is pretty simple. If I'm going to have my database handle my sessions that are currently active for the users that are logged in (probably through a table that has a column with the UserID and the SessionID) how can I use PHP to generate a completely random Session ID? I will then pass that Session ID into a httpOnly cookie.

I assume this will work with my Angular front-end as I can use the withCredentials boolean option on every http request since I won't have direct access to the Session ID cookie.

So when a user wants to access a restricted area, their http request will contain the Session ID cookie and my PHP will determine what their User ID is by doing a lookup on the CurrentSession table. This will then allow PHP to determine the user's access level.

All this will be done over a HTTPS connection but I think I will still have to worry about CSRF attacks so I will probably use the Double Submit Cookie method as Angular already provides support for it.

So I guess my main question is, would simply finding out a way to generate a unique Session ID with PHP work for securing my app? Or would somehow encrypting the Session ID so only my PHP can decrypt it be a good idea, so in case somehow an attacker got access to the Session ID from the cookie, it would solely be an encrypted version of it, so it would be useless.

Upvotes: 0

Views: 159

Answers (1)

Freddythunder
Freddythunder

Reputation: 51

I would suggest using PHP's session_start() which will handle the session in its entirety including any cookies that need to be written to maintain the session depending on your particular connection at the time.

All you need to do is put this at the very top of your PHP scripts:

<?php
session_start();

A PHP constant "SID" should be available to get your session id which you could store in MySQL for other purposes if you wanted to - but it may not be necessary. You can also use session_id() as well.

Upvotes: 1

Related Questions