简体   繁体   English

将用户是否登录的检查放入php中的包含文件中

[英]Putting the check for if user is logged in or not into an include file in php

I have a code to check whether the user is logged in or not this is the code call the userlog.php 我有一个代码来检查用户是否登录,这是代码调用userlog.php

    <?php
if (!isset($_SESSION['idx'])) { 
if (!isset($_COOKIE['idCookie'])) {
$logOptions = '<a href="register.php">Register Account</a>
&nbsp;&nbsp; | &nbsp;&nbsp; 
<a href="login.php">Log In</a>';
echo $logOptions;
}
}
else{//do something }

This code works fine if I include this code in all the files as it is. 如果我将此代码包含在所有文件中,则此代码可以正常工作。 When I put the file into a separate file and include it into all the files it is not executing properly. 当我将文件放入一个单独的文件并将其包含在所有文件中时,它没有正确执行。 The else condition is different for all the files so I have If I start the else block in the include file itself then when I end the else block in this file (call index.php) then there is error 所有文件的else条件都不同所以我有如果我在包含文件本身启动else块然后当我结束此文件中的else块(调用index.php)时出现错误

syntax error, unexpected '}' in index.php on line 43

and when I put the else in the index.php file and if block in the userlog.php then following error occurs 当我把else放在index.php文件中,如果在userlog.php中阻塞,则会发生以下错误

syntax error, unexpected T_ELSE in index.php on line 9 

So how can I use the include to manage this case. 那么如何使用include来管理这种情况呢。

You are just missing the proper open and close braces. 你只是错过了正确的打开和关闭括号。 In the code you have given your else block is not eding. 在您给出的其他块的代码中没有eding。 You have commented out that part of code. 你已经注释掉了那部分代码。 I am referencing this line 我正在引用这一行

else{//do something }

Create the proper if-else block and include, that should solve this error. 创建正确的if-else块和include,这应该可以解决这个错误。

In an IDE like eclipse you can quickly jump to the matching braces using Ctrl + Alt + P to verify. 在像Eclipse这样的IDE中,你可以使用Ctrl + Alt + P快速跳转到匹配的大括号来验证。

inc.php inc.php

<?php
$loggedIn = FALSE;

if ( !isset($_SESSION['idx']) ) { 
    if ( !isset($_COOKIE['idCookie']) ) {
        $logOptions = '<a href="register.php">Register Account</a>
        &nbsp;&nbsp; | &nbsp;&nbsp; 
        <a href="login.php">Log In</a>';
        echo $logOptions;
    }
} else {
    $loggedIn = TRUE;
}
?>

index.php 的index.php

<?php
require_once('inc.php');

if ( $loggedIn == TRUE ) {
    // do your stuff
}
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM