Page 1 of 1

Session

Posted: Fri Jan 19, 2007 5:55 pm
by Garcia
I am trying to retrieve the user id of a member from my login page, but I do not know how set the variable and retrieve it on that page.

Log In:

Code: Select all

<?php
//login page
session_start();
session_register("username", "id", "gid");
require ("config.php");

//if entered blank form returns error
foreach ($_POST as $field => $value)
{
	  if ($value == "")
		{
		  $blanks[] = $field;
		}
}

if (isset ($blanks) )
{
	$message = "Following fields are blank. Please enter the required information:   ";
	foreach ($blanks as $value)
	{
		$message .= "$value, ";
	}
	extract ($_POST);
	include ('login_form.php');
	exit();
}

//Define variables.
$username = trim($_POST['username']);
$password = trim($_POST['password']);

//time to select information
$sql ="SELECT `username`,`password`, `id`, 'gid' FROM members WHERE username = '$username' AND password = md5('$password')";
$result = mysql_query($sql, $con);
$row = mysql_fetch_assoc($result);
mysql_error();

//We check if username and password is correct
$num = mysql_numrows ($result);
if ($num != 0)
{
	print "Welcome $username - your log-in succeeded!";
}
else
{
	print "Wrong username or password";
}

?>
Here is the page where I want the sessions to appear. Now would I need to start a query to receive the users id and if I did how would I accomplish this?

Code: Select all

<?php
require ('config.php');
session_start();
header("Cache-control: no-cache");

print $username;

print $id; //Not sure how to set this one up


?>
Any help would be appreciated.

Thanks!

Posted: Fri Jan 19, 2007 7:16 pm
by aaronhall
session_register() is deprecated -- use the $_SESSION superglobal instead.

Code: Select all

// page 1
session_start();
$_SESSION['username'] = $username;

Code: Select all

// page 2
session_start();
echo $_SESSION['username'];

Posted: Sat Jan 20, 2007 2:11 pm
by Mightywayne
I'm a noob, so take this as you will. A tutorial I recently *shudders* completed, did the last page like this.

Code: Select all

session_start();
if(!session_is_registered(username)){
header("location:main_login.php");
}
So basically, if the session wasn't registered, they'd go back to the main page. All I know is you gotta put that above PHP on every page you've got requiring a login.

Hope I was of help.

Posted: Sat Jan 20, 2007 2:54 pm
by aaronhall
The session_is_registered() relies on session_register() (deprecated). Here's the simple way to move to $_SESSION:

Code: Select all

session_start();

// check if username/password is correct
if(user authenticated...) {
   $_SESSION['logged_in'] = true;
}
On subsequent pages:

Code: Select all

// insert this on all pages where the users must be logged in
session_start();
if(!$_SESSION['logged_in']) {
   header('Location: http://www.mysite.com/main_login.php');
}
Here's a good tutorial from Zend if you're interested: http://devzone.zend.com/node/view/id/646