Search code examples
phpsessiongoogle-oauthtwitter-oauthfacebook-oauth

Check if authenticated user is active in session php


Hi I am using below Login / Register systems on my website

1. Login via website (i.e. example.com)
2. Login via Facebook
3. Login via Twitter
4. Login via Google

Now when user logged in via example.com then i set value in session as below

session_start()
$_SESSION['auth_yes_exm'] = "Username from mySQL DB"

and when user logged in via FB,Twitter or google then i set value in session as below

session_start()
$_SESSION['oauth_user'] = "Oauth Username"

Now, there is a page Orders on which i check if user is authenticated then only show the order details to him / her and it is applicable as below:

session_start(); 
if(!(isset($_SESSION['auth_yes_exm']) && $_SESSION['auth_yes_exm']!='')){
   header('location: login.php');
   exit();
 }

How can i also check that if Oauth user is logged in and show order detail to him as well?

I tried as below but it redirects to login page always

session_start(); 
if(!(isset($_SESSION['auth_yes_exm']) && $_SESSION['auth_yes_exm']!='') || 
!(isset($_SESSION['oauth_user']) && $_SESSION['oauth_user']!='')){
   header('location: login.php');
   exit();
 }

Please get me out of this. I am setting Oauth session as different variable beacuse i require it to be used at some other places also.


Solution

  • Either use

    if($_SESSION['auth_yes_exm'] || $_SESSION['oauth_user']) {
        //Show the page
    }
    

    while setting whichever index you don't want to log the user in as null when you assign to the other index, or use this:

    if(
        (array_key_exists('auth_yes_exm', $_SESSION) && $_SESSION['auth_yes_exm']) || 
        (array_key_exists('oauth_user', $_SESSION) && $_SESSION['oauth_user'])
    ) {
        //Show the page
    }
    

    which will avoid undefined offset warnings and require you to only define one index at a time.