Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Check if user is logged in with a function

I'm working on a website and the index page checks if the user is logged in or not with this piece of code:

if (!$_SESSION['login'] && $_SESSION['login'] == "") {
include_once($_SERVER['DOCUMENT_ROOT'] . "/login/");
} elseif ($_SESSION['login'] == 1) {
include_once($_SERVER['DOCUMENT_ROOT'] . "/main/");
}

But I want it to look cleaner, then I started wondering if was possible to achieve something like this with a function:

checklogin($_SESSION['login']);

I don't have much experience with functions, so i'm sorry if my question looks stupid, so thanks in advance.

like image 281
user2733576 Avatar asked Aug 30 '13 15:08

user2733576


2 Answers

Try this

if(check_login()) {
  echo 'You are in!';
} else {
    header('Location: login.php');
    exit;
}

function check_login () {
    if(isset($_SESSION['login'] && $_SESSION['login'] != '') {
       return true;
    } else {
       false;
    }
}
like image 181
user2533445 Avatar answered Sep 20 '22 17:09

user2533445


Just use empty:

if ( empty($_SESSION['login']) ) {
    include_once($_SERVER['DOCUMENT_ROOT'] . "/login/");
} else {
    include_once($_SERVER['DOCUMENT_ROOT'] . "/main/");
}

Or condense it:

include_once $_SERVER['DOCUMENT_ROOT'].(empty($_SESSION['login']) ? "/login/" : "/main/");
like image 30
Joseph Silber Avatar answered Sep 19 '22 17:09

Joseph Silber