Joann
Joann

Reputation: 1377

How do I make a page aware that the viewer is logged in or not?

I am building a membership site... I just got thru the login page and I can now login and logout. However that alone doesn't protect all my pages in the root.. How do I go about this? I'd like to set it up like so when the viewer isn't log-in, the page that's being opened would say "Log in first blah3x"... Any help pls??? :-(

Upvotes: 0

Views: 93

Answers (2)

walkthroughthecloud
walkthroughthecloud

Reputation: 101

The next thing you need to do is build up your access control list (ACL). The list might be a list of pages that can only be viewed when authenticated. The next thing is to persist the authentication token (could be username) through SESSION or COOKIE then lookup your ACL if the page where the current user is requesting requires authentication and then route it somewhere, could be the homepage, if it's in the list. Your ACL can be stored to a database, SESSION or COOKIE. Make sure o encrypt all information saved on a COOKIE.

Take the following example. You can simply add this as an include file to the top of your every page.

<?php
//this could be acl.php
//this could be saved to $_SESSION, $_COOKIE or database
$acl = array("members"=> 1,
             "comment"=> 1);

 //assuming that you have saved the username authenticated into a $_SESSION for persistence
if (!isset($_SESSION["username"]) && isset($acl[$page]) {
   //user is not logged in
   die("Please log-in");
} 
?>

Sample usage,

<?php
 //this could members.php
 $page = "members"; //or you can leverage $_SERVER["SCRIPT_NAME"] to get the pagename automatically
 include_once("acl.php");
?>

On more advance usage of ACLs, the source often uses roles or the user itself to define it. When you load it to the page though, it always user specific.

Upvotes: 1

David Yell
David Yell

Reputation: 11855

I would, when the user logs in, create a session object and store some information in there. Something which identifies the user.

$_SESSION['User']['logged_in'] = true;

Then, in the top of my page, I'd probably throw in a check.

if(!isset($_SESSION['User']['logged_in']){
  header('Location: login.php');
}

That would redirect anyone not logged in, to your login page. Do think about how to better secure your application, as this is very rudimentary and wouldn't really be ideal for any production environments.

Upvotes: 3

Related Questions