Page 1 of 1

PHP login script help

Posted: Mon Aug 31, 2009 2:44 am
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

Re: PHP login script help

Posted: Mon Aug 31, 2009 3:05 am
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();
}
?>

Re: PHP login script help

Posted: Mon Aug 31, 2009 3:18 am
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.

Re: PHP login script help

Posted: Mon Aug 31, 2009 3:36 am
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.