Click to See Complete Forum and Search --> : Basic PHP Sessions Problem


AlexFZ
08-09-2007, 09:02 AM
Hello,

I am teaching myself PHP, and am trying to make a basic admin center type script. Everything works fine, except either the session will not register, or the script is not checking properly for the session.

The way it is setup, is with three scripts.

The first script is index.php: This is the main admin center page. Right now, all it does is check to see if you are logged in or not. If you are logged in, it shows a message saying "this is where the admin center would be". If you are not logged in, it displays the file ./templates/login.php, which is just an HTML form. I don't know why I named it .php. The third script is called when you submit the form in .templates/login.php, it does all the login work and sets a session if the username and password matches the database entry.

index.php:
<?php
if (!isset($_SESSION['login'])) {
include './templates/login.php';
}
else {
echo 'This would be the admin center';
}
?>

Form Handler:
<?php
include '../config/connect_info.php';
include '../config/mysql_connect.php';

$username = $_POST['username'];
$password = $_POST['password'];

$query = "SELECT * FROM admin WHERE glogin='$username' AND gpassword = '$password'";
$result=mysql_fetch_array(mysql_query($query));

if ($result) {
session_start();
$_SESSION['login']=1;
echo 'Login success. You will now be redirected to the admin cp.<br><br>
Browser not redirecting? <a href="index.php">Click here.</a>';
}
else {
echo 'Login unsuccessful. <br><br>
Username and password did not match. <br><br>
<a href="index.php">Click here to go back</a>';
}

include '../config/mysql_close.php';
?>

All that happens if that index.php just keeps calling .templates/login.php, even if the message says "login success" when I try it.

Any help would be greatly appreciated. Thanks!

ellisgl
08-09-2007, 09:03 AM
try putting session_start() at the top of the index.php script.

AlexFZ
08-09-2007, 09:06 AM
If I do that, it will always say that you are logged in even if you never entered anything.

ellisgl
08-09-2007, 09:08 AM
replace if (!isset($_SESSION)) with
if($_SESSION['login']==1)

AlexFZ
08-09-2007, 09:13 AM
Thanks a lot, that works perfectly :)

ellisgl
08-09-2007, 09:15 AM
no problem..