[solved] Login with sessions not working

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
smudge
Forum Contributor
Posts: 151
Joined: Sun May 20, 2007 12:13 pm

[solved] Login with sessions not working

Post 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.
Last edited by smudge on Fri Jul 27, 2007 12:32 pm, edited 1 time in total.
User avatar
TheMoose
Forum Contributor
Posts: 351
Joined: Tue May 23, 2006 10:42 am

Post 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'];
}
smudge
Forum Contributor
Posts: 151
Joined: Sun May 20, 2007 12:13 pm

Post by smudge »

Thanks for the fast reply. That did the trick!
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Remember that standards compliance dictates the usage of a full URL for all header() based redirections.
Post Reply