Safe way to create a session

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
swraman
Forum Commoner
Posts: 58
Joined: Thu Nov 06, 2008 12:33 am

Safe way to create a session

Post by swraman »

Hi,

I really dont know how to create a login session.

I have a login script that checks identity, but how do I make it so that the user doesnt have to login every page to get to restricted material?

If I were to use a cookie, what would I put in it so that it would be safe? ie. so someone cant create the cookie in notepad and use it to fool the site?

thanks

Raman
operationOverkill7
Forum Newbie
Posts: 2
Joined: Thu Jan 22, 2009 3:30 pm

Re: Safe way to create a session

Post by operationOverkill7 »

Hey,
I found this quite useful. It uses cookies to keep the user logged in.
http://www.phpeasystep.com/workshopview.php?id=6

Edit: I normally do read users full post. I must have blanked over the last 2 lines. Sorry.
User avatar
Stryks
Forum Regular
Posts: 746
Joined: Wed Jan 14, 2004 5:06 pm

Re: Safe way to create a session

Post by Stryks »

I'd suggest using sessions before going with cookies.

With cookies, all data you store will be kept with the client, where they are free to edit at will.

With sessions, a session ID is stored with the client in a cookie, but all the information you store is safely tucked away on the server. The user can tamper with their session ID, but without knowing a specific current session id, it'd be pretty amazing that anyone could fluke it into someone else's login, especially with a good security plan.

Log a user in ...

Code: Select all

// very top of page
session_start();
$_SESSION['is_logged_in'] = true;
Make sure user is logged in ...

Code: Select all

// very top of page
session_start();
if(!isset($_SESSION['is_logged_in']) || $_SESSION['is_logged_in'] != true) {
   // User is not logged on - bounce to a public access area
   header('Location: http://www.example.com/');
   exit();
}
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Safe way to create a session

Post by califdon »

Very nice explanation of Sessions vs. Cookies, Stryks!

Just to make sure the questioner understands, every script that is used in the session must have session_start() at the beginning (or at least before checking whether the requestor is already logged in).
Post Reply