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.
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;
}
}
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/");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With