Jump to content

How to check if user is logged in...


TutorMe

Recommended Posts

I am using a script from a login tutorial online to create an admin section for a website.  In this tutorial, there is a page called register.php, that should only be accessible if the user is logged in as administrator.

 

I tried to use a simple if statement like this:

<?php
if($logged_in){
   echo 'Logged in as '.$_SESSION['username'].', <a href="logout.php">logout</a>';
   echo 'Use the form below to register new administrators.';
   //code for register.php would be here, but it is pretty long, so I excluded it
}else{
   die(You are not logged in.)
}
?>

however, this doesn't work because the code I am using doesn't use "<?php" to open each php segment, and there are several sections of "<? //code ?>" throughout the page.

 

Can anyone tell me a way to make the page visible only when logged in?

Link to comment
https://forums.phpfreaks.com/topic/68097-how-to-check-if-user-is-logged-in/
Share on other sites

I have tried that, but the code has many different sections, which stop the if statement from working.  I'll give you an example:

?>

<h1>Registered!</h1>
<p>Thank you <b><? echo $uname; ?></b>, your information has been added to the database, you may now <a href="main.php" title="Login">log in</a>.</p>

<?
   }
   else{
?>

<h1>Registration Failed</h1>
<p>We're sorry, but an error has occurred and your registration for the username <b><? echo $uname; ?></b>, could not be completed.<br>
Please try again at a later time.</p>

<?
   }
   unset($_SESSION['reguname']);
   unset($_SESSION['registered']);
   unset($_SESSION['regresult']);
}

if(isset($_SESSION['registered'])){
/**
* This is the page that will be displayed after the
* registration has been attempted.
*/
?>

<html>
<title>Registration Page</title>
<body>

<? displayStatus(); ?>

 

This is just a portion of the code.  Does that help you understand what I'm saying about multiple sections of code?

I don't know if this will help you but it's worth a try

 

Here is a function to auth a user

function is_authed()
{
    if (isset($_SESSION['username'])
    {
         return true;
    }
    else
    {
         return false;
    }
}

 

You could put something like this on the page where only registered admins are allowed access

<?php
   if (!is_authed()) 
   {
       print ('You are not permitted to view this page, <a href="index.php">click here</a> to go back.');
   }
   else
   {
       //do the rest of the code
   }	    
?>

 

What i did with mine is add some extra code to the function to check the user level (stored in database) and if the user level is not a certain level, display the error message

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.