PHP login script help

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
hoopstars
Forum Newbie
Posts: 1
Joined: Mon Aug 31, 2009 2:31 am

PHP login script help

Post by hoopstars »

I'm new to php...

I currently have a login script and a couple of html files.

What i want is that whenever my html files are accessed directly (i.e http://www.domain.com/file.html) it will redirect users telling them that they need to login first before they can view the page.

how will I do that?

thanks in advance for your help
AlanG
Forum Contributor
Posts: 136
Joined: Wed Jun 10, 2009 1:03 am

Re: PHP login script help

Post by AlanG »

You should use sessions. Here's a very simple example.

Code: Select all

<?php
session_start();
 
if($username == 'root' && $password =='password')
    $_SESSION['active'] = true;
else
    $_SESSION['active'] = false;
 
// Now we check for the logged in user and redirect if necessary
if($_SESSION['active'] == false) {
    header("Location: http://www.example.com/login.php");
    exit();
}
?>
Last edited by AlanG on Mon Aug 31, 2009 3:31 am, edited 1 time in total.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: PHP login script help

Post by Benjamin »

You'll need to call session_start(); on every page where sessions will be used. You cannot send any output to the browser before starting the session. Also, I recommend using braces on conditional statements to prevent confusion and hard to debug code in the future.
AlanG
Forum Contributor
Posts: 136
Joined: Wed Jun 10, 2009 1:03 am

Re: PHP login script help

Post by AlanG »

astions wrote:You'll need to call session_start(); on every page where sessions will be used. You cannot send any output to the browser before starting the session.
session_start() ... WOW, I think it's bed time... Staring at this screen for far too long. Can't believe I missed that. Thanks for the correction. :)
astions wrote:Also, I recommend using braces on conditional statements to prevent confusion and hard to debug code in the future.
You sound like my brother. :) I like the compactibility of the single statement. But I definitely see your point.
Post Reply