Brad Hazelnut
Brad Hazelnut

Reputation: 1621

PHP Session vars inside of a class

I have the a user object class that I have the following function in. The function works and it lets a user login and everything just fine. But when I try to create a session variable within the function it doesn't seem to work. I create the session variable in the function, and then in the calling page that calls the function I do a var_dump($_SESSION) and it's blank. Is it not possible to create session variables inside of a class?

 public function userLogin() {
     $success = false;
     try{
        $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); 
        $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        $sql = "SELECT * FROM users WHERE username = :username AND password = :password AND status = :status LIMIT 1";

        $stmt = $con->prepare( $sql );
        $stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
        $stmt->bindValue( "password", $this->password , PDO::PARAM_STR );
        $stmt->bindValue( "status", "active" , PDO::PARAM_STR );            
        $stmt->execute();

        $valid = $stmt->fetchColumn();

        if( $valid ) {
            $success = true;
                session_start();
                // Set user session variables
                foreach($stmt as $row) {

                    $_SESSION["username"] = $row['username'];
                    $_SESSION["role"]     = $row['role']; 
                }

        }

        $con = null;
        return $success;
     }catch (PDOException $e) {
         echo $e->getMessage();
         return $success;
     }
 }

Upvotes: 0

Views: 77

Answers (1)

raidenace
raidenace

Reputation: 12826

$_SESSION is a superglobal variable and accessible everywhere.

You need to use session_start() before settings sessions if you are not doing so already.

Also check the two conditions you have to see if it is getting inside those scopes:

if( $valid ) {

foreach($stmt as $row) {

Upvotes: 1

Related Questions