I'm trying to learn PHP, I've managed a basic news script but I want to add user functionality to it.. I don't know why, but this isn't keeping me logged in. When I enter the correct details I get told, thanks you're logged in. but when i go to example.php it redirects me back to login.php because apparently im not logged in.. login.php: <?php session_start(); include("/home/phpmedia/public_html/news/config.php"); // we'll encrypt passwords in the db using md5(); if(isset($_POST['submit'])) { $user = $_POST['username']; $password = $_POST['password']; $check = mysql_query('SELECT * FROM `users` WHERE `username` = \''.$user.'\''); $check2 = mysql_num_rows($check); if($check2!=1) { echo "you don't exist, register pls."; } else { $row = mysql_fetch_array($check); // because it;'s encrypted in the db... $password = md5($password); if($row['password'] = $password) { // NOT SURE ABOUT SESSION REGISTERING.. THIS IS HOW I *THINK* ITS DONE session_register('username'); session_register('password'); $_SESSION['username'] = $row['username']; $_SESSION['password'] = $row['password']; echo "thanks, you're logged in"; } else { echo "bad password"; } } } else { echo '<form action="login.php" method="post"><input name="username" type="text" /><input name="password" type="password" /><input type="submit" name="submit" value="submit" />'; } ?> PHP: example.php: <?php session_start(); include("/home/phpmedia/public_html/news/config.php"); if(isset($_SESSION['username'])) { $query = mysql_query('SELECT `username`,`password` FROM `users` WHERE `username` = \''.$_SESSION['username'].'\''); $check = mysql_num_rows($query); if($check==0) { header('Location: login.php'); // corrupt login data } else { $row = mysql_fetch_array($query); if($_SESSION['password'] == $row['password']) { echo 'logged in'; } } } else { echo 'please login kthx bye'; } // rest of the script here ?> PHP:
Remove the calls to session_register(). It isn't needed anymore - all you need to set session variables is a prior call to session_start() and then the usual assignment to the $_SESSION array, as you've done.
Helo just checking. is this section of your code working alright because it looks like one of those heart breaking girls if($row['password'] = $password) { // NOT SURE ABOUT SESSION REGISTERING.. THIS IS HOW I *THINK* ITS DONE session_register('username'); session_register('password'); $_SESSION['username'] = $row['username']; $_SESSION['password'] = $row['password']; echo "thanks, you're logged in"; }
To tell wether someone is logged in within your login script once you have checked the password etc and created the session then you can insert in a mysql table useronline information. Remember to place a timestamp in aswell so you can delete people who inactive for a while.