I have the function as follows:
$sid = mysql_real_escape_string( $_COOKIE['session_id'] );
if( $sid ) { session_id( $sid ); }
// Start session
if( !session_start() ) { die( 'Session could not be started.' ); }
$sid = session_id();
// Validate session id
$user = $this->validateSessionId( $sid );
if( $user ) {
if( !$user['uid'] ) {
trigger_error( '`Services->__construct()` - Could not find user by session id \''.(string)$sid.'\'.',
E_USER_ERROR );
}
$_SESSION['uid'] = $user['uid'];
$_SESSION['user_name'] = $user['name'];
$_SESSION['user_email'] = $user['email'];
$_SESSION['user_created'] = $user['created'];
}
// If no valid session id, user is anonymous
else {
$_SESSION['user_name'] = 'Anonymous';
$_SESSION['user_created'] = time();
}
When a user first logs in, a cookie is created for them called session_id with the id of their current session. This id is also added to a database table. My understanding is that the session eventually expires on both the client and the server, but a cookie and a database entry can be set to last as long as I’d want.
validateSessionId checks a table of session ids in the database. If the session is found, and hasn’t last been accessed more than 30 days ago (it’s removed from the table if so), an associative array from the user list representing the user associated with that session id. That user’s data is then loaded into the current session.
Am I understanding the workings of this correctly?
The whole
session_id()business can be avoided. PHP will automatically check for the presence of a session cookie when you call session_start(), and retrieve the session’s ID at that time. You’re just duplicating what’s already done for you.Your code presumes that the cookie PHP is sending out to track the session is actually a permanent cookie. Usually PHP sends out a session cookie only (e.g. delete when browser is closed). As such, the user will not have ANY session cookie when they come back to the site, and will get a brand new session each time.