Page 1 of 1

[solved] Login with sessions not working

Posted: Fri Jul 27, 2007 12:22 pm
by smudge
Hello, I'm working on a project that requires an authorized login. I have the login form and basic script to handle this, but the sessions don't seem to be working. There are 3 files right now: login.php is the login form, index.php is the page index, auth.php checks to see if the user has logged in.

login.php:

Code: Select all

<?php

$auth_p="test";
$auth_u="test";

$ref=$_SERVER['HTTP_REFERER'];
$msg="";

if (isset($_POST['username']) && isset($_POST['password'])){
  session_start();
  session_register('auth_username','auth_password');
  $_SESSION['auth_username']=$_POST['username'];
  $_SESSION['auth_password']=$_POST['password'];
}

if (isset($_SESSION['auth_username']) && isset($_SESSION['auth_password'])){
  if ($_SESSION['auth_username']==$auth_u && $_SESSION['auth_password']==$auth_p){ //just for now. will eventually loop through DB
    if(preg_match("domain.com\/",$ref)){
      header('Location: $ref');
    } else {
      header('Location: http://domain.com/index.php');
    }
  } else {
    $msg="<br /><span style='color:red'>Bad username or password</span>";
  }
}

?>
index.php as of now only include()s auth.php

auth.php:

Code: Select all

if (!isset($_SESSION['auth_username']) || !isset($_SESSION['auth_password'])){
  header('Location: login.php');
} else {
  $username=$_SESSION['auth_username'];
}
But if I login with the correct info (test/test) it takes me back to login.php. I've not done much with sessions, so any help on this would be much appreciated.

Posted: Fri Jul 27, 2007 12:30 pm
by TheMoose
Any page that requires the use of session variables needs to have the session_start(); function called before the variables can be used.

So in your auth.php, put:

Code: Select all

session_start();
if (!isset($_SESSION['auth_username']) || !isset($_SESSION['auth_password'])){
  header('Location: login.php');
} else {
  $username=$_SESSION['auth_username'];
}

Posted: Fri Jul 27, 2007 12:32 pm
by smudge
Thanks for the fast reply. That did the trick!

Posted: Sat Jul 28, 2007 4:58 pm
by feyd
Remember that standards compliance dictates the usage of a full URL for all header() based redirections.