Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set up a secure PHP Session

In a similar vein to my previous question - I'm not a very experienced PHP Programmer. I know nothing about Sessions or Security (other that what I learnt an hour ago about md5 and sha1 with salt).

I have a login system, and I wish to create a session that stores and encrypted string of a user's username mixed with a timestamp. I know how to create the string, but I know nothing about Sessions or how they work.

I've spent the past hour Googling for a solution, but they all seem too basic or outdated, I'm looking for something that has concrete security, but is also simple (due to my inexperience).

How would I (on administrative pages) check to see if the user has logged in, assuming this string is encrypted?

I know there are similar questions but I need an answer from a complete layman's point of view as I do not know how to implement this solution.

Thanks for any help you can offer

like image 835
Dan Hanly Avatar asked Feb 04 '26 22:02

Dan Hanly


2 Answers

I wish to create a session that stores and encrypted string of their username

Why? Unless you are decrypting it, then there's no advantage over using a hashed or even random value. And if you're decrypting it then the key must be stored in your data too - so its just security by obscurity.

How would I (on administrative pages) check to see if the user has logged in, assuming this string is encrypted?

Don't store the username in a session variable until it has been authenticated. Then if the variable is populated you know that the user has been authenticated.

like image 194
symcbean Avatar answered Feb 07 '26 13:02

symcbean


After the user logs in, store in the session its identifier. On the administrative page, read this session value and use it to query the database to determine if the user has admin privileges. If he doesn't show an error.

Obviously, this admits variations (e.g. storing in the session a User object that already contains info about administrative status of the user).

The data in $_SESSION cannot (unless you do something very dumb) be tampered with by the client, since it's stored in the server. You don't need to encrypt or hash anything.

like image 44
Artefacto Avatar answered Feb 07 '26 14:02

Artefacto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!