Ways to keep objects' info across different pages

0 Ibrahim Tuzlak · March 14, 2015
Hello.

I've been experimenting with sessions and login systems recently. One thing that I can't decide is the way to keep session informations across multiple pages.
To be more precise, say I have an object  $session of the class named Session. The object should contain methods associated with what an user can do while logged in, along with different types of informations about session and the user, stored in non-public variables. One of the informations is whether the user is logged in or not, of course.

Now, when the user visits another page, the object must be recreated:
$session = new Session;

but the stored informations from previous page are lost. In fact, the object is as empty as if the user never logged in.

I would like to hear your thoughts on the following solutions (or if you have your own!):

1. Storing in cookies
Pros: Available on every page until it expires, or is deleted
Cons: it's client-side and therefore, not secure (any workaround?)

2. Storing the whole object in $_SESSION
if(isset($_SESSION['sessionObject'] ) ) {
$session = $_SESSION['sessionObject'];
} else {
$session = new Session;
}



3. Store relevant-to-the-problem info in $_SESSION and retrieve it via constructor
class Session {
public function __construct() {
if(isset($_SESSION['user_data'] ) ) {
$this->userName = $_SESSION['user_data']['user_name'];
// And so on
}



4. Store all sessions' informations into a database




I'm thankful if you read this. I'm looking forward to see your opinion.

Post a Reply

Replies

Oldest  Newest  Rating
0 Ibrahim Tuzlak · March 16, 2015
Thanks for the response, Alan.

I did a little bit of Googling on memcache after reading it. It appears that memcached might be just what is needed for keeping (not only) sessions alive.
While doing so, I also came across this link http://dormando.livejournal.com/495593.html which explains a good way to combine database and the cache for the best results.
+2 Alan Johnson · March 15, 2015
For persistent data you'll need to use a database. Obviously this creates an overhead, but you can alleviate the strain on your server by caching your data, with tools like memcache and APC.

$_SESSION is persistent and can be used for things like if the user is logged in, their username, when they were last active... etc.

You shouldn't be using cookies for storing sensitive user information. They are on the client side, as you mentioned, and can be easily modified/deleted. Use sessions or a database instead.
  • 1

PHP

107,029 followers
About

Server-side, HTML embedded scripting language used to create dynamic Web pages.

Links
Moderators