Log in

View Full Version : Question about getting session vars



kathycam
05-19-2012, 05:22 PM
Hello

I have created this function to set a session variable with a random number (just to see if I anything was working):

function StartSession()
{
session_unset();
session_destroy();
$_SESSION = array();

session_start();
$sSessionID = rand(RAND_START,RAND_END);
session_register('$sSessionID');
}

Then I try to call it:
echo "Sessions = ". $_SESSION['$sSessionID'];

and nothing is set.

How do I do this?

Thanks.

traq
05-19-2012, 08:24 PM
...you're doing a lot of unnecessarily complicated and somewhat counter-productive stuff. For example, you don't really need to use a custom function to start your session. Then, your StartSession() function destroys any existing session - you're starting a new session each time. Third, the code you posts doesn't actually start a session (you never call your function).

<?php
// you need to start your session _before_ any output to the user.
// unless you _need_ a custom session id, just let PHP create one itself.

// start the session.
session_start();

// (don't use session_register(). it is deprecated and was actually removed in 5.4.)

// using session variables:
if( empty( $_SESSION ) ){
// if no session exists (i.e., this is the first page visit),
// we'll start with a value of 1.
$_SESSION['view_count'] = 1;
}else{
// if a session exists, we'll increment the view count.
$_SESSION['view_count']++;
}
// then print out how many page views there have been this session:
print "Number of times you have viewed this page during this session: {$_SESSION['view_count']}";

vikasbook
05-22-2012, 08:20 AM
Thanks #Traq this quite sufficient reply from you I know

Two ways : 1. manually write each page session_start()

2. all site level set value 1 in php.ini file session_auto_start()