0

I wrote this script. It is working, but when I leve the page, or when I return to the page, sessions are not being saved. What I am doing wrong?

login.php

<?php
session_start();
require 'classes.php';

//if user is not yet authorized
if ($_SESSION['user']->iduser == null) {
    $dbhandle = mysql_connect($hst, $usr, $pass);
    if (!$dbhandle) {
        die('Could not connect: ' . mysql_error());
    }
    $selected = mysql_select_db($dbName, $dbhandle)
            or die("Could not select the database");

    $result = mysql_query(" query ");
    $resultArray = mysql_fetch_array($result);
    $num_rows = mysql_num_rows($result); //count how many rows returned
    //if 0 rows returned, then login was failed
    if ($num_rows == 0) {
        die('Error! Access denied. Incorrect username or password.');
    } else { //if username and password match
        $_SESSION['user'] = new user();
        $_SESSION['user']->iduser = $resultArray{'iduser'};
        $_SESSION['user']->fname = $resultArray{'fname'};
        echo 'Dear ' . $_SESSION['user']->fname . ', you succesfully logged in!';
    }
    //if user is already logged in
} else {
    echo 'You already logged in!<br>Your email is: ';
}
?>

class user

<?php
class user {
    public $iduser = null;
    public $fname = null;
    public $lname = null;
    public $email = null;
    public $password = null;
    public $permission = null;
}
?>
4

1 回答 1

3

You need to "require (classes.php)" before the session starts.

(Simple answer :) )

Reason: the session is decoded when you call session_start. For an object to be unserialized correctly, then the class must be already defined. Ergo you need to define the class before session_start - swapping those two lines around should do it.

http://php.net/manual/en/oop4.serialization.php

于 2012-09-13T02:36:48.367 回答