Page 1 of 1

Sessions question

Posted: Tue Sep 11, 2007 4:02 pm
by Brandensmith1
I'm trying to make a login page that directs the user to a page where they can edit the news mysql table. The problem I have is I can't seem to get the members page to get the $username of the person logged in. I am probably completely wrong from what I have so far, but from my little knowledge of what I've been practicing it looks right to me.

login.php

Code: Select all

<?php
session_start();
include 'dbdata.txt';
mysql_connect($db_host, $db_user, $db_pwd);
mysql_select_db($db_name);
$username = htmlentities($_POST['username']);
$password = htmlentities($_POST['password']);
if(isset($_POST['username']) && $_POST['password'])
{
	$query = "SELECT * FROM users WHERE user_name = '$username' AND password = '$password'";
	$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
    if(mysql_num_rows($result) == 1)
	{
	$_SESSION['login'] = $username;
	$_SESSION['password'] = $password;
    	header("Location: members.php");
    	}
//the form and stuff down here
}
?>
members.php

Code: Select all

<?php
session_start();
include 'dbdata2.txt';
mysql_connect($db_host, $db_user, $db_pwd);
mysql_select_db($db_name);
if (!isset($_SESSION['login']))
{
	header('Location: login.php');
}
else if(isset($_SESSION['login']))
{
	echo "<html><head><title>Make Some Damn News!</title></head><body> Welcome <b>$_SESSION['login']</b> <a href=\"logout.php\">logout</a>";
}
else
{
echo "I guess I don't know how to work Sessions";
}
?>
It members.php right now opens a blank page, it does not return to the login.php like its suppose to. HELP! It's driving me crazy 8O

Posted: Tue Sep 11, 2007 4:14 pm
by feyd
A blank page would suggest a parse error unless your page logic simply wouldn't print something at all.

session_write_close() may be of interest. Also, note that header() based redirection requires full URLs, http:// and all to maintain standards compliance.

Posted: Tue Sep 11, 2007 4:14 pm
by Christopher
This is a fairly common problem, but the solution is not obvious.

If you redirect you are still within the same HTTP request. The session is only written when the request is complete. That means that the values set on the first page have not been written when the second page reads the session file. Use session_write_close() on the first page to write the values to the session file before redirecting.

Posted: Tue Sep 11, 2007 7:16 pm
by Brandensmith1
thanks for the help, when my webhost comes back online I'll test it out :D

Posted: Tue Sep 11, 2007 7:46 pm
by Brandensmith1
yep that fixed it, thanks a lot guys :)