[英]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. 我没有太多的功能经验,所以如果我的问题看起来很愚蠢,我很抱歉,所以提前谢谢。
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;
}
}
There is what you need: 有你需要的:
function userCheck()
{
return (isSet($_SESSION['login']) && $_SESSION['login']);
}
if(userCheck())
include_once($_SERVER['DOCUMENT_ROOT'] . "/main/");
else
include_once($_SERVER['DOCUMENT_ROOT'] . "/login/");
Disregarding the fact of whether or not your approach makes sense, I think this would do what you expect: 无论你的方法是否有意义,我认为这会做你期望的事情:
function checklogin($login){
if (!$login && $login == "") {
include_once($_SERVER['DOCUMENT_ROOT'] . "/path/");
}
}
// **** call to the function
checklogin($_SESSION['login']);
// ****
You can use this function: 你可以使用这个功能:
function checklogin() {
return (isset($_SESSION['login'])) ? true : false;
}
then on pages you want to check whether the user is logged in or not, you can: 然后在要检查用户是否登录的页面上,您可以:
if(checklogin() === true){
//here you would put what you want to do if the user is logged in
} else {
//this would be executed if user isn't logged in
header('Location: protected.php');
exit();
//the above would redirect the user
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.