-2

I am using the $_SESSION global variable on each page on my application so that I can control access to my site with login functionality. Instead of using the following path that searches for TRUE else FALSE, as showed in the example below, how can you reverse the condition?

<?php
if (isset($_SESSION['id'])) {
    echo $_SESSION['id'];
} else {
    echo "You are not logged in!";
}
?>
Bricked
  • 115
  • 11
  • 2
    Do you mean `!isset()`? If you add a `!` to the beginning of your `if` statement, it turn it around. – Nytrix Apr 03 '17 at 23:07
  • 1
    Take a look at [**logical operators in PHP**](http://php.net/manual/en/language.operators.logical.php), specifically the `not` operator. This is more or less universal for all programming languages, though. – Qirel Apr 03 '17 at 23:09
  • Thank you. What I really want to do is if display my site page only if the user has an active session. I have the login functionality working, but now that I try to insert this piece of code on every page, I can't get it to work. Maybe that is the subject of another topic – Bricked Apr 04 '17 at 02:22

3 Answers3

4

Look at logical operators in the PHP manual, your problem is solved and explained very well there. So please, take a look.


In this case

If you want to turn your if statement around, you should do this:

<?php
if (!isset($_SESSION['id'])) {
    echo "You are not logged in!";
} else {
    echo $_SESSION['id'];
}
?>

Simply put: ! means not.

In this particular case, you are using the ! operator, which means that you are turning around your if statement normally goes through if it's true. So, if it's isset() but you add the ! operator, you check if it's notisset(), in a way, where the "not" is a !.


The manual

The manual puts it like this: if(!$a){} is true if $a is not true.

Nytrix
  • 1,133
  • 11
  • 21
  • 1
    Although I know what "this" is, you should add some text, preferably with references, and a description what this change means and why its significant; it might not be obvious to future readers. – Qirel Apr 03 '17 at 23:10
  • @Qirel - I edited my original post to help future readers. I think this is what you wanted. – Bricked Apr 04 '17 at 12:15
1

I think you're looking for this? You just have to negate isset with !, so you're essentially saying IF NOT / ELSE instead of IF / ELSE

 <?php
 if ( !isset( $_SESSION['id'] ) ) {
      echo "You are not logged in!";
 } else {
      echo $_SESSION['id'];
 }
JDev518
  • 662
  • 6
  • 15
1

An exclamation sign ! equals "not", like

if (!isset(...etc...
Johannes
  • 53,485
  • 15
  • 52
  • 104