Click to See Complete Forum and Search --> : Login script using sessions


cjc1055
08-17-2005, 09:14 PM
Ok, I am trying to create a way to securely log into my site then view certain pages that are only viewable when you are logged in. Even if you knew that the secure page was page2000.php, if you type it in it should deny you access unless you log in.

Here is what I have so far. I have created the database in mysql and have added a username and password to use.

I have created the login form:

<form action="validate.php" method="post">
<input type="text" maxlength="10" name="username">
<input type="password" maxlength="10" name="password">
<input type="submit" name="submit" value="Submit">
</form>

and I have created the validate.php (validates the login) and it works perfectly, so thats done, now how do i get it to redirect to the secure pages and keep those pages secure?

Here is the code for the validate.php, this should look familar :)

<?php session_start();
include 'config.php';
include 'connect.php';

$_SESSION['logged'] = 0;

if (isset($_POST['submit'])) {

$sql = "SELECT * FROM `cflpass` WHERE `username` = '". $_POST['username'] ."'";
$sql = mysql_query($sql);
$result = mysql_fetch_assoc($sql);

if($_POST['username'] == $result['username'] &&
$_POST['password'] == $result['password']) {
$_SESSION['user'] = $result['id'];
$_SESSION['logged'] = 1;

print 'login success';
}
else {
print ' Login Failed';
}
}

?>

rch10007
08-17-2005, 10:06 PM
You could add something like this to each page you want secured:


<?
if (!$_SESSION['logged'] === 1)
{
include ( "login_page.php");
exit;
}
else
{
include ( "secured_pages.php" );
}
?>


how do i get it to redirect to the secure pages and keep those pages secure?

You can do an include() in the validating section of your script where you have: print 'login success';

or you can use: header("Location: http://www.example.com/");

make sure to capitalize the "L" in Location.

cjc1055
08-17-2005, 10:18 PM
it printed the following error about a thousand times

Notice: Undefined variable: _SESSION in c:\Inetpub\wwwroot\cflwebdesign\pw\view.php on line 2


I tried a couple of different things based on your script with no luck.

rch10007
08-17-2005, 10:26 PM
I didn't intend for you to cut and paste exactly what I had - did you?

It was just for an idea but from the error you have it is saying that you session variable hasn't been created - so this means that:

your login script isn't setting the variable
or
you're forgetting to add session_start() at the top of every page that will use sessions
or
there's a typo in your variable
or
a bunch other stuff

put your code up for the session pages or upload them so we can take a better look at what the problem is since it can be alot.

cjc1055
08-18-2005, 07:21 AM
I am using the code you provided and I tried adding session start at the top but gave me an error, session alread started, ignoring sessoin start.