Luke Berry
Luke Berry

Reputation: 1947

PHP Sessions problem, help please

I'm making an item shop for a game of my friends, when accessing the shop, I have it check the session to see if you are logged in, if you are it will take you to the shop, if you aren't it will give you a login page, the way I do that is like this.

<?php 
  if($_SESSION['LoggedIn'] == 1)
  {
      //Shop stuff here
  }
  else
  {
    //Login stuff here
  }
?>

However, it shows me an error when they aren't logged in.

Notice: Undefined index: LoggedIn in C:\wamp\www\shop\shop.php on line 29, line 29 being the if($_SESSION['LoggedIn'] == 1) I want to stop this from happening without disabling the PHP errors, any idea how?

Upvotes: 1

Views: 138

Answers (6)

Amati
Amati

Reputation: 1532

...or the politically incorrect answer if (@$_SESSION['LoggedId'] == 1) {...} ;)

Upvotes: -1

Fopa L&#233;on Constantin
Fopa L&#233;on Constantin

Reputation: 12363

to use $_SESSION it is important to start the session first with the instruction session_start ();

session_start();

if($_SESSION['LoggedIn'] == 1)
{
  //Shop stuff here
}
else
{
//Login stuff here
}

if this statement is not present the session will not be open, that means that every informations that you have already put there will be inaccessible, so be careful while reading or writing in $_SESSION

Upvotes: 0

Arkh
Arkh

Reputation: 8459

To add some variety to the answers, I'd like to give you empty :

if(!empty($_SESSION['LoggedIn'])){
    //Shop stuff here
}
else{
    //Login stuff here
}

Upvotes: 1

nik
nik

Reputation: 3678

You can use

if(isset($_SESSION['LoggedIn']))
{
    //Shop stuff here
}
else
{
    //Login stuff here
}

Upvotes: 0

Delan Azabani
Delan Azabani

Reputation: 81412

Do this instead:

if (isset($_SESSION['LoggedIn']) && $_SESSION['LoggedIn'] == 1)

Upvotes: 3

halfdan
halfdan

Reputation: 34234

Use isset():

if(isset($_SESSION['LoggedIn']) && $_SESSION['LoggedIn'] == 1) {
  // ...
}

Upvotes: 2

Related Questions