Jump to content
xisto Community
Sign in to follow this  
trauMatic

PHP Sessions, Help how to use sessions?

Recommended Posts

The php session is really quite easy to do. The session data is stored on the server so you don't need to use any other resource like mySQL.

 

The session will save whatever variables and values you want to the server.

 

To start a session do the following:

session_start();
To set a variable and value to the session do this:

$_SESSION[username] = 'vujsa';
If you want to set a session variable but give it no value, do the following:

session_register('counter');
There isn't really any reason to register a variable and not add a value but there it is anyway.

 

Using that same variable, instead of just registering it without a value, we can set the value to a number like one. Like so:

$_SESSION[counter] = 1;
Then later we could increase that variable each time a page is loaded.

$_SESSION[counter]++;
This will add 1 to the value of the session variable named "counter".

 

If you do this each time a page is loaded, you will keep track of the number of times the user has loaded one of your pages during the current session.

 

But you'll need to check to see whether or not the variable counter has already been set before assigning a new value to it.

<?php session_start();if ($_SESSION[counter]) {    $_SESSION[counter]++;}else {$_SESSION[counter] = 1;}?>
Remember, the count is only for the current session. If the user leaves and their session expires, the count will be lost.

 

Also, in order to use sessions, the user must accept your cookie. If their browser can not use cookies or they do not accept your cookie, your sessions will not work. You should be sure to design a backup in the acse that your sessions don't work.

 

I assume that you want to use your sessions for things like keeping track of a member after he logs in. If that is the case, you'll need to have a login script that uses a database and has some degree of user authentication in place.

 

You'll always start a session when someone comes to your site. The only difference between a guest and logged in member is that the member's seesion will have a logged in variable.

 

For example, after the user has entered his correct username and password, your login script should set a session variable like so:

$_SESSION[logged_in] = 'yes';
Then on your member only pages, you would check to see if the member is logged in or not:

<?phpsession_start();if ($_SESSION[logged_in] == 'yes') {    build_member_page();}else {    build_login_page();}?>
Of course, the two functions (build_member_page() and build_login_page()) would need to be real functions that actually built a page.

 

You could also add a variable for member type if you wanted to make certain pages only availible to Admins or Staff.

[/hr]

 

This is a very basic session system. It won't last long after the user leaves and it can't determine what permissions each user has.

 

For best results, you should a database with the sessions. mySQL is a free and widely availible database system that is offered on most hosting accounts including the hosting accounts here at Xisto. The best part of using mySQL, is that it is much easier than the old days with flatfile databases (all of the data was stored in a text file with seperators like "|" ).

 

You can set the session ID in the database to be the same as the session id on the server. This way, you can store more perminent data than with the session alone. This way you can save user preferences or simple keep track of whick user file is associated with the session being used.

 

If you have a database table that stores the username used for what session, then you could use the session ID to retrieve member information like user preferences so that your user can customize the look of your site to their taste. That way if your user ste their background color to navy blue, it would always become navy blue as soon as they logged in.

 

It would be difficult for me to explain more about how to use sessions in PHP without knowing for sure what you want to do with it.

 

For more information, I suggest that you look at the php manul regarding PHP sessions.

http://us2.php.net/manual/en/function.session-start.php

 

Hope this helps! :)

 

vujsa

Share this post


Link to post
Share on other sites

Nice explanation. Sessions work a lot like Post or Get variables when you're setting or retrieving values from a variable. I was wondering do you have to put session_start() at every page? I'm pretty sure you do, but it seems kinda redundant. Once you set a session it should be there.Another function is session_name(), which can either return the name of the session or set it by passing a string or string variable as an argument.

Share this post


Link to post
Share on other sites

Yes, you have to use the session_start() function on every page to let the script know that you are either starting or continuing a session. There isn't any reason for PHP to work with sessions in many cases so instead of running the server's session engine all of the time and usually unnecessarily, you simply tell it the maybey 20% of the time it is used. The reason we use session_start everytime is that the programmer of this function had the foresight to make our lives easier.If we used session_start() to start our session but a diferent function to continue the session, we would then have to add a check on every page to see if we should start a new session or continue an old session.vujsa

Share this post


Link to post
Share on other sites

Couple of things about sessions...

I think it was already mentioned but deserves to be emphasized: do not use sessions without a reason. Generally speaking, it is better to use cookies to store simple variables. Yes, cookies have a bad reputation but you are going to have to use cookies with sessions anyways (I'll get back to that later) so it would be kind of pointless to save the users preference of to show or not to show the help box in a session which ID is stored in a cookie anyways. Why? Because sessions are not all that server friendly. The data of PHP sessions are stored on the hard disk of the server which means it is slow to access and takes processing time on the server. And as usual for a site with sessions, all your users are going to be storing some information in the session. This is not to say that don't use sessions, you should because they are handy, but don't use them for tasks for which cookies suit better.


The sessions ID and how to transfer it. Session IDs are essential as they are the one and only way of identifying which session belongs to which client. As default PHP tries to use a cookie to store the session id, but failing that it will append it to the URL as a get variable. This is not a good thing. Many PHP sites use GET variables to identify different pages and so on, and the php session id appended to the query makes it even longer (thus unacceptable to some systems) and can mess up your system. And for sites no using GET variables... well with session they now use it. And as you might know, using GET variables isn't always the optimal thing to do as search engines tend to have problems with them.

Basically you have two options instead of the default PHP method. Either you set

ini_set('session.use_trans_sid', false);
,which prevents the session ID to be transmitted in the end of the URL, or you code the transmission of the ID in the url in your system. The first option would mean that a user that doesn't accept cookies won't be able to use the session and the latter means that you have to do the session id transmitting to every link pointing to another part of your site.

First option is not that bad: it is reasonable to expect your visitors to have cookies enabled if you are offering a service that requires sessions, a login system for instance. The second... well a lot of work. And you end up having urls with session id's stuck to them. By the way, it is recommeded that you don't initiate session for robots; the content requiring to have a session does not need to be in google anyways.


And it's always nice to end with some discussion on security. Sessions are a nice way to do a login system. But in itself it is not enough. Setting a session variable "logged_in" into boolean true is not sufficient login system for practicalyl anything. Sessions are ridiculously easy to copy, if your friend sends you a URL to a webstore and the URL contains the session id (his id) it might be that you can by simply opening the page see the contents of his shopping cart: remember, in session system, the server only recognises the session by the id. So you need to take this into account.

A secure way is to do it is by using an additional method of authenticating. For many simple systems, simply just keeping the records of which session ID belongs to which IP address is good. Sure, user behind same proxies seem identical this way but it rules out a big part of the users. Plus there is IP spoofing. Also having another variable for identification in a cookie helps too. This would be a random number for example. Yes cookies can be manufactured but it requires the malicious person to know the contents of the cookie. This kind of security measures should suffice for simple authentication for a shopping cart for example. And don't forget session length, shorter the length more secure the session becomes. On the other hand it's not nice to keep typing your username and password or lose your shopping cart every ten minutes. So be reasonable.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.