PhP Session Issues

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
chizeng
Forum Newbie
Posts: 11
Joined: Sun Feb 28, 2010 10:52 pm

PhP Session Issues

Post 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
rmrbest
Forum Newbie
Posts: 8
Joined: Fri Feb 26, 2010 2:32 am

Re: PhP Session Issues

Post 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.
xtiano77
Forum Commoner
Posts: 72
Joined: Tue Sep 22, 2009 10:53 am
Location: Texas

Re: PhP Session Issues

Post 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.
chizeng
Forum Newbie
Posts: 11
Joined: Sun Feb 28, 2010 10:52 pm

Re: PhP Session Issues

Post by chizeng »

I really appreciate everyone's help! Thanks. Those suggestions did clear up the problem and successfully made a session.
Post Reply