how to use session to identify if user is login?

Hi Everyboyd,

I am currently working on a ecommerce project and i would like to know we can use session to identify if a user is logged in or not?

What i need is tips and guidance to sort it out myself.

thanks

If you have not taken the time to at least learn the basics, you’re not ready to ask questions.

I would suggest you start with http://php.net/manual/en/function.session-start.php and look at the various session options then you will be able in the future to do something like:

In your config.php or utilities.inc.php file
[php]/* Use $user for sessions variable */
$user = isset($_SESSION[‘user’]) ? $_SESSION[‘user’] : NULL;[/php]
Then on any page you don’t want a non-user to access you would simply do something like:
[php]if (!$user) {
header(“Location: login.php”);
exit();
}[/php]

Of course you will need to have a way to login a person, here’s how I currently do mine:
[php] public function read(array $data = NULL) {
$this->query = ‘SELECT id, username, password, security_level, first_name, last_name, email, home_phone, cell_phone, gender, birthday FROM users WHERE username=:username’;
$this->query_params = [’:username’ => $data[‘username’]];

    try {
        $this->stmt = $this->pdo->prepare($this->query);
        $this->result = $this->stmt->execute($this->query_params);
    } catch (Exception $ex) {
        die("Failed to run query: " . $ex->getMessage());
    }

    $this->stmt->setFetchMode(PDO::FETCH_OBJ);
    $this->user = $this->stmt->fetch();

    if ($this->user) {
        $this->loginStatus = password_verify($data['password'], $this->user->password);
        unset($data['password']); // Unset the password:
        unset($this->user->password);
    }

    if ($this->loginStatus) {
        $_SESSION['user'] = $this->user; // Set the session variable of user:
        return TRUE;
    } else {
        return FALSE;
    }
}[/php]
If you have not taken the time to at least learn the basics, you're not ready to ask questions.

The link that Strider64 gave is one I remember reading when I first started!, here is another one.

http://www.w3schools.com/php/php_sessions.asp

Just another note on sessions, get into the habit of naming your sessions before you start them, otherwise if you run multiple projects on the same dev environment and you are using the same code you may confuse yourself! You may also want a session for a backend system and a session for a frontend system which you are running in the same browser.

[php]
session_name(“MyCoolProject”); //this will make sure the variables in this session are definitely for this project
session_start();

[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service