One solution is cookies. Cookies are files residing on the CLIENT'S computer that store variables set by a particular website. This file can only be accessed by the website, or domain, that issued the cookie. The problem with cookies is that they are an untrusted medium. Users can modify cookie data, and cause unwanted problems with your app.
A better solution is sessions. Sessions are a lot like cookies, however they reside on the SERVER machine, and cannot be edited directly by the client. When you use sessions, a session ID is stored either in a cookie on the client side, or in form data that is sent with each request. This ID links the client to a particular file or record, depending how the session is stored.
Here is a quick primer to get you using sessions!
First! You must initialize the session at the start of your application. This makes sure that the session is started before any output is made. You must start the session before headers are sent to the client, so the best approach is on your main page at the very top, start the session this way;
Once you start the session, you can now start using session variables. To set a session variable, is much like an associative array. You can access the variable the same way.For example, say we want to store a variable of 'username' and give it the value of 'joeyadms', we would do the following;
<?php // Always Start our session session_start(); $_SESSION['username'] = 'joeyadms'; $username = $_SESSION['username']; echo $username;
This would output joeyadms.
Remember, when you set a session variable. It is persistent as long as the session is maintained (determined by logout,exit browser, and php.ini options). So you can set a session variable on one page, and call it the same way on an entirely different page!
By default, PHP stores the session ID in the client's cookie. In my opinion, the cookie is the best place, storing it in form values can be unreliable, and has more potential to be unsafe. You can change your 'php.ini' settings to change the cookie variable name used if you like;
; Name of the session (used as cookie name). session.name = PHPSESSID
There is a big problem with sessions, the same as with cookies. Session Hijacking, and Session Fixation are attacks directed straight at them.
Session Hijacking happens when an attacker gets the session id of an user who has logged in, he then spoofs his ID to be that of the victim. The attacker has now successfully assumed the identity of the victim.
Session fixation works almost the same way. However, this time, the attacker sends an specially crafted url, or uses a forwarder to set the session ID of a victim, the victim then logs in, and the attacker uses the ID he already has to Hijack the session.
To protect against these attacks, make sure you session_regenerate_id() whenever a user logs in. Also adding some fingerprint check protection is best.
For a great Session Security Class , check the snippets here for my SessionSecurity addition.