I’m kinda new to PHP and having a little trouble with user sessions.
I have an ask_login.php
page where I simply ask the user to enter his/her login details through a form.
Once he/she logs in I want to save his/her login session until he/she decides to logout.
But for some reason I can’t manage to save the user session, because I tried to print the username while navigating to another part of the site and the username doesn’t show up.
Here’s my code:
ask_login.php
<h1>Login</h1>
<form method="post" action="login.php">
<p><input type="text" name="username" value="" placeholder="UserID"></p>
<p><input type="password" name="password" value="" placeholder="Password"></p>
<input type="submit" name="commit" value="Login"></p>
</form>
login.php
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if(!empty($username) && !empty($password)) {
$queryget = mysql_query("SELECT * FROM users WHERE id='$username' AND password='$password'");
$numrows = mysql_num_rows($queryget);
if($numrows != 0) {
//save session
$_SESSION['id'] = $username;
} else if (empty($username) || empty($password)){
echo "Wrong username/password";
echo "<script>alert('Username/Password are incorrect');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
}
}
?>
logout.php
<?php
session_start();
session_destroy();
header('Location: index.php');
?>
You only store the user id in the $_SESSION
:
$_SESSION['username'] = $username;
Furthermore you will need to call session_start()
every time. Therefore most PHP programmers use a header.php
file that is called each time and does some bookkeeping in the beginning of a page.
You should start the session on every page where you want to use the array $_SESSION
.
To test wither or not you have the information stored in the session, do this:
session_start();
print_r($_SESSION);