noob php question - sessions

Soldato
Joined
6 Mar 2008
Posts
10,079
Location
Stoke area
Hi all,

I'm rusty with html and css but I want to branch out to PHP, SQL and javascript.

Currently building a employee area for work as a project, it's the way I learn best. I want people to login and any actions they do (training, editing a file, taking a phone call etc) to be logged. Would this just be a case of using a session to hold their username and applying it when needed?

Or am I completely misunderstanding what a session is?
 
That would be a good place to use a session. As the name implies, it should be used for any temporary data that is relevant to the current active user session.

In your case, you would be using it to cache user data (username) because it wouldn't make sense to fetch it from the database every time.
 
A session is basically per-user memory that persists between http requests.

When you start a session, a unique id is generated and stored on a cookie in the user's browser. That cookie is then sent by the browser on each subsequent request, so that the server can identify the client (you can use query params instead of cookies for the session ID but it's not a good idea).

The actual data you store in the session is persisted on the server side, which by default is simple file-based storage, but can be switched to a relational DB or some other datastore if required.

For simple authentication, you could have a login form that sets some flag in the session when the user successfully authenticates. You would then check for that session var on any page you need to be secure.

e.g. in you login form submit handler:

Code:
if ($_POST['password'] === $password) {
    $_SESSION['authenticated'] = true;
}

and then in the pages you want to secure:
Code:
if (!$_SESSION['authenticated']) {
    // redirect to login page
}

There's a lot more to having a secure site than the above, but it should at least get you started.
 
Last edited:
thanks for that :)

I'm running through this guide at the moment:

http://www.formget.com/login-form-in-php/

Using shiftedit.net as the IDE and it seems awesome so far.

Issues with the script is that it looks like it isn't protecting the password (my understanding is that md5 isn't really secure and to use hash/salt for them but I need to read more on this) and that it is using mysql_connect() which is deprecated.
 
thanks i'll take a look :)

that's the problem I find with online info, lots of bad and outdated stuff, and when learning you have no idea it's rubbish.

Spot so many bad python tutorials it's unbelievable!
 
Back
Top Bottom