Hi, I'm new to php, but I'm trying to implement a basic user system on my site. I'm having some trouble keeping a PHP session when I change pages (or something like that) where the logged in varible (id
) isn't showing up as being defined, so a logged-in user doesn't actually log in.
This is how I log the user in
<?php
if ($_POST['username'] && $_POST['password']) {
include_once "mysql.php";
$username = ereg_replace("[^A-Za-z0-9]", "", $_POST['username']);
$password = ereg_replace("[^A-Za-z0-9]", "", $_POST['password']);
$password = md5($password);
$sql = mysql_query("SELECT * FROM members WHERE username='$username' AND password='$password' AND email_activated='1'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
while($row = mysql_fetch_array($sql)) {
$id = $row["account_id"];
session_register('id');
$_SESSION['id'] = $id;
$username = $row["username"];
session_register('username');
$_SESSION['username'] = $username;
mysql_query("UPDATE members SET lastlogin=now() WHERE account_id='$id'");
//$_SESSION id is set to the correct value here
header("Location: profile.php?id=$id"); //supposed to redirect the user, now logged in. But doesn't keep the session I just registered.
}
//rest of login form code after here (html)
This is how I try to check if the user is logged in
and display menus
<?php
session_start();
$toplinks = "";
if (isset($_SESSION['id'])) { //id always returns null, and is never displayed
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '<a href="profile.php?id=' . $userid . '">' . $username . '</a> •
<a href="account.php">Account</a> •
<a href="logout.php">Log Out</a>';
} else {
$toplinks = '<a href="join.php">Register</a> • <a href="login.php">Login</a>';
}
//other site code (html)
So what am I doing wrong to have the login not set up a session? I've looked through other tutorials and they do it just the same way as this. Did I miss something?
Thanks