...

View Full Version : A question on how PHP handles sessions and how it should be declared.



rix
09-05-2005, 08:52 AM
I'm just learning PHP (being a java and jsp programmer) and i'm busy doing a site. Now my problem comes in on how PHP handles sessions. Now for the login to be remembered on the other pages, i set two session variables (the one is the user id and the other is just some check boolean variable just to make sure someone doesn't try and bypass the session or something). now i can't seem to retrieve those variables right and it's starting to grate me.

<?php
//session_start();
session_register("myuid");
session_register("theusersname");
session_register("thestupidlylongcheckvariable");
?>
Do i have to put this declaration on top of every page that i want to use the session variables on ? (this is one of the pages after the login have been made, and is supposed to read that info)

gsoft
09-05-2005, 09:04 AM
Well firstly before any session can be initiated you need to use session_start(); basically this just starts the session and any existing sessions can be seen.

Now you appear to be using the older way of using sessions I highly suggest avoid doing it that way there is a much easier way.



session_start(); // must be called on each page (not file) you want to have sessions available

// create some sessions
$_SESSION['mynewsession'] = 1;


If the session mynewsession does exist the value will be overwritten if it doesnt it will be created an initialized. Now say on page x.php you want to view that sessions value



session_start(); // must be called on each page (not file) you want to have sessions available

echo $_SESSION['mynewsession'];


That will output 1 as long as the session has been created. Also by using sessions in this way the other session functions such as session_unregister/session_unset/session_destroy cant be used to delete/destroy the session. You must use the function unset



session_start(); // must be called on each page (not file) you want to have sessions available

unset($_SESSION['mynewsession']);


Dont do this



unset($_SESSION);


As that will destroy the session variable and a server restart will be required.

Kid Charming
09-05-2005, 09:08 AM
You should only use session_register if the register_globals .ini is on, and it's off by default. Instead, try using session_start() (http://us2.php.net/manual/en/function.session-start.php) and putting your sessions variables directly into the $_SESSION array.

Like gsoft said.

rix
09-05-2005, 10:40 AM
thanks for the quick response guys! u've saved my (and the ppl around me)'s life
i hate it when your coding and in the end it's a stupid mistake that makes the silly thing not work.

thanks again!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum