简体   繁体   中英

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

    <?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

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

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

So how can I use the include to manage this case.

You are just missing the proper open and close braces. In the code you have given your else block is not 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.

In an IDE like eclipse you can quickly jump to the matching braces using Ctrl + Alt + P to verify.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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