Jump to content

Sessions And Cookies


smerny

Recommended Posts

Hey, I'm trying to do cookies/sessions for the first time, I read the w3schools tutorial pages on them... but it doesn't really give a good application on how to use them on a website. After just reading the tutorial it seems like I could JUST keep retrieving the cookie and not have to store anything to session? It also seems like if I wanted to do session, I would have to make sure to have a retrieve cookie on every page of the website in case they go to that page first? and then store the cookie variables to session?Can someone please show me with example code of what is a good way to use cookies/sessions on a website?

Link to comment
Share on other sites

Sessions use the cookie process so you don't have to mess around with cookies yourself. When using sessions, it's probably best to ignore the fact that it works using cookies. Work just with the $_SESSION array and you will be fine.All protected parts of your site will need some code to check a session value. But it doesn't need to be much.Your login script will look something like this:

// access your user databaseif ($good_user) {	session_start();	$_SESSION['user'] = $user_id;}

The top of all your protected pages will look something like this:

session_start();if (!isset($_SESSION['user'])) {	header('Location: login.php');	exit;}

Link to comment
Share on other sites

Close. The cookies get sent to your page as part of the original HTTP request. session_start() accesses the session data stored on the server. If it finds an active session ID that matches the session ID in your cookies, it then copies the session data into the $_SESSION array. (If it does not, it creates a new session.)I think I understand some of your confusion now. Only the session ID is stored as a cookie on the browser. All the values that your script assigns to the $_SESSION array are stored (invisibly) on your server. That is what makes the system secure. Data you put into the $_SESSION array never gets passed to the browser, because that would be unsafe.When a session expires, your server's automatic garbage collector deletes the session data.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...