Page 1 of 1

PhP Session Issues

Posted: Mon Mar 01, 2010 11:51 pm
by chizeng
Hi all,

I created a session in a class function like this:

Code: Select all

class Login {
    function setSession($userName) {
    session_start();
        $_SESSION['userName'] = "$userName";
    }
 
I called it and tried to access the session variable like this:

Code: Select all

 
<?php echo $_SESSION['userName']; ?>
 
It doesn't seem to work for some reason. Am I calling it right? Thanks,

Chi

Re: PhP Session Issues

Posted: Tue Mar 02, 2010 2:20 am
by rmrbest
Hello, you put it well, $ _SESSION[ 'username'] = $userName; as the other way around this by adding to the session with a string value $username.

Re: PhP Session Issues

Posted: Tue Mar 02, 2010 5:49 pm
by xtiano77
You should use the "session_start()" at the begining of the .php file and not inside a class method. Unless I am mistaken the "session_start()" should be the first line of code on the page. If you want to assign values to the $_SESSION["VARNAME"] you can do that after the session has been created. The example below is what I am using on my pages:

Class File

Code: Select all

 
<?php
class Sessions {
     public function createSession($userInformation){
          if(is_resource($userInformation)){
               $user = @mysql_fetch_array($userInformation, MYSQL_ASSOC);
               $_SESSION["USERNAME"] = $user["username"];
 
               //remainder code here...
 
          }else{
               header("Location: http://www.whateverPage.php");
          }
     }
}
?>
 
I use a method simiar to the one above at the end of the authentication page in order to establish the session and assign their values. After that I only call the "session_start()" at the begining of each page and that does it for me.

Code: Select all

 
<?php
session_start();
 
$session = new Sessions();
 
//remainder of your code here...
 
$session -> createSession($resource);
?>
 
Just my two cents.

Re: PhP Session Issues

Posted: Tue Mar 09, 2010 8:06 pm
by chizeng
I really appreciate everyone's help! Thanks. Those suggestions did clear up the problem and successfully made a session.