Losing session values after header redirection - php

I'm using $_SESSION to keep my users logged in after they have logged in.
When they return to the homepage, they at first appear to be logged in, but after refreshing the page once, they are no longer logged in.
NOTE: I'm still learning PHP programming so please don't mind that most of my code is rather, noobish.
Index.php Code:
<?php
session_start();
$UserOnline = "Guest";
if (isset($_SESSION['username'])) {
$UserOnline = $_SESSION['username'];
}
echo $UserOnline;
?>
Login.php Code:
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username)) {
$InvalidLogin = "Please submit a username";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
} elseif (empty($username)) {
$InvalidLogin = "Please submit a password";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
}
require 'required/connect.php';
$result = mysqli_query($con, "SELECT * FROM users WHERE username='$username'");
$row = mysqli_fetch_array($result);
if ($password == $row['password']) {
$_SESSION['username'] = $username;
echo "Successful Login!";
echo "<br>";
echo "<a href='index.php'>Return to HomePage?</a>";
} else {
$InvalidLogin = "Your info didn't match ours!";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
}
?>
I have tested on the login.php page if the user is in a session there, and I always get the correct return value. The issue is that after I refresh once on the Index.php page, the user is no longer in a session.
Is there something I'm forgetting, or am I not using the $_SESSION correctly? Is there another error that I simply do not know about?

Put exit; after header('location:.....') and your problem will be solved.

Issue is resolved. Error was found in Index.php. Set Variable $UserOnline before the if(isset($_SESSION['username'])). Thanks for the help guys

Related

Admin Check Script Not Working

so i have done this script below to check if logged in user is not admin and redirect non-admin to 404 page, but keep admin in the same page and show him his stuff
<?php
session_start();
$username = $_SESSION['username'];
$loggedin = $_SESSION['loggedin'];
if ($username != "administrator") {
header("location: 404.php");
exit;
} else {
include 'include/usermenu.php';
}
?>
but my admin is also redirected to 404(he shouldn't be), so could anybody tell me what have i done wrong? and by the way im having just one admin, so thats why its username
To test, change your code as follows:
<?php
session_start();
$username = $_SESSION['username'];
$loggedin = $_SESSION['loggedin'];
if ($username != "administrator") {
##header("location: 404.php"); exit;
print "normally I would redirect you because username is $username ";
} else {
include 'include/usermenu.php';
}
?>
See if username is coming up as a blank or some alternate spelling?

$_SESSION not carrying across php pages

I am having a problem with the $_SESSION function in my php website. I set the function and then try to access it in another page, but it just comes up as blank.
This is the file login.php where I set the $_SESSION
<?php
session_start();
?>
<html>
<?php
$email = $_POST['email'];
$password = $_POST['password'];
$con = mysqli_connect("host","user","pass","db");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
if ($email && $password){
$result = mysqli_query($con, "SELECT * FROM users WHERE email='$email'");
$numrows = mysqli_num_rows($result);
if ($numrows != 0){
//username exists
$row = mysqli_fetch_row($result);
if ($password != $row[2]){
print 'Incorrect password<br />';
$error = TRUE;
}
else {
//password is correct
echo "You're in! <a href='member.php'>Click</a> here to enter member page";
$_SESSION['email'] = $email;
}
}
else {
//email not found
print 'Sorry, that email cannot be found.<br />';
$error = TRUE;
}
}
else {
die('Please enter an email and password<br />');
$error = TRUE;
}
if ($error){
print '<a href=index.php>Go Back</a>';
}
?>
</html>
And this is the member.php file.
<?php
session_start();
if (isset($_SESSION['email'])){
$username = $_SESSION['email'];
echo "Your email is ";
echo $username;
}
?>
When I press the link to go the the member.php page via the link, the page is completely blank, presumably suggesting that the $_SESSION['email'] has nothing in it.
Please let me know where I am going wrong, and how to rectify the issue.
Any help would be much appreciated.
If anyone wants to see how the site is actually working, please go here.
Add session_start(); before the HTML in login.php to set it
You need this call at the very top of login.php, not halfway through.
session_start();
Add this to the very top of the login.php page:
<?php
session_start ();
?>
From the PHP documentation:
"Note:
To use cookie-based sessions, session_start() must be called before outputing anything to the browser."
http://us3.php.net/session_start
If that still doesn't work edit this line:
echo "You're in! <a href='member.php'>Click</a> here to enter member page";
to be like this instead:
echo "You're in! <a href='member.php?" . htmlspecialchars(SID) . "'>Click</a> here to enter member page";
http://us3.php.net/manual/en/session.idpassing.php
Z

PHP Page isn't storing cookies

I am new to php and I am making a basic login script.
All I want to do is log in and have the cookie for my user_id stored.
It works on all of my other pages, except my index page which is one directory up.
So on my index page, I have this if statement:
<?php
if (!isset($_COOKIE['user_id'])) {
sign_in();
} else {
echo "You're already logged in!";
}
?>
No matter what I do, the sign_(); function always shows.
But here's the kicker:
On my login script, the whole thing goes through as if I successfully logged in.
I send it back to this page using:
header("Location: ../index.php");
(It is up one directory)
However, when I make it link to a page in the same directory, it registers the cookie and everything is alright.
header("Location: show_user.php");
If you want a hands on view, you can go to http://patti-bee2.dcccd.edu/coleman/wonder%20penguin/php/signup.php to make your account. And http://patti-bee2.dcccd.edu/coleman/wonder%20penguin/php/show_user.php to view it. And notice how the index page doesn't register the cookie.
How I tried to set the cookie:
if (isset($_POST['usernamelogin'])) {
$user_login = $_REQUEST['usernamelogin'];
$pass_login = $_REQUEST['passwordlogin'];
$pass_login = trim(crypt($pass_login, $user_login));
$login_query = sprintf("SELECT username, user_id FROM user WHERE username = '%s' and password = '%s';", mysql_real_escape_string($user_login), mysql_real_escape_string($pass_login));
$loginresult = mysql_query($login_query, $dbConn);
echo $login_query;
if (mysql_num_rows($loginresult) == 1) {
$userinfo = mysql_fetch_array($loginresult);
$username = $userinfo['username'];
$userid = $userinfo['user_id'];
setcookie('username', $username);
setcookie('user_id', $userid);
header("Location: show_user.php");
exit();
} else {
echo "Couldn't find your account!";
}
}
Please excuse my unrefined page and amateur mistakes. I have a lot to learn.
Any ideas?
Thank you for your time.
Check if you have the cookie with the following
<?php
var_dump($_COOKIE);
//if (!isset($_COOKIE['user_id']))
if (empty($_COOKIE['user_id']))
{
sign_in();
}
else {
echo "You're already logged in!";
}
?>

PHP unset and desroyed session starts itself

I got a little problem with my php code here... Can you please help me out?
The problem is that when i, in my logout.php, unsets and destroys sessions, it works the first time i load some of my other pages.. but when i refresh right after, the session is started again, which i dont really understand? Because i have my page to look for a session with a specific name. Here is my code:
Login.php:
<?php session_start();
//Get username and password
$email = $_POST['email'];
$password = $_POST['password'];
//Sorting special characters away, with exception of "-" and "."
stripslashes($email);
$email = preg_replace('/[^A-Za-z0-9#\.\-]/','', $email);
//Getting the password from the database
$link = mysqli_connect("****", "****", "****", "****");
if (mysqli_connect_errno($connect))
{
echo "Connection Failed!";
mysqli_close($connect);
}
$sql = "SELECT * FROM admins WHERE email = '". $email . "'";
if ($result = mysqli_query($link, $sql))
{
while ($row = mysqli_fetch_row($result))
{
$db_password = $row[2];
}
mysqli_free_result($result);
}
mysqli_close($connect);
//Compare DB-password to entered password
if ($db_password == $password)
{
$_SESSION['admin'] = $email;
header("Location: ../index.php");
exit();
}
header("Location: index.php");
exit();
?>
Logout.php:
if(!isset($_SESSION['admin']))
{
header("Location: ../index.php");
exit();
}
else
{
session_unset();
session_destroy();
echo '<h1>You have been succesfully logged out!</h>';
exit();
}
Index.php:
if (isset($_SESSION['admin']))
{
echo '<div id="admin"><br>
<h3>'.$_SESSION["admin"].'</h3>
<span>Admin panel</span><br>
<span>Log out</span>
</div>';
}
And yes, i got session_start() on top of every one of my pages.
As you can see in the index.php, i want some code to be written if $_SESSION['admin'] is set. And when i destroy the session in my logout.php, and goes to index.php, it works the first time i load the page. But i i refresh, the code reappear, which means the session must have been set again, somehow! But i dont know why? Please help!
EDIT: I have put the whole code of the login.php now. The rest of the other 2 pages, is pure HTML. What i have posted is all my PHP code!
It might because of the PHPSESSID cookie. just try it by removing PHPSESSID cookie from browser
if(!isset($_SESSION['admin']))
{
header("Location: ../index.php");
exit();
}
else
{
session_unset();
session_destroy();
setcookie('phpsessid','value',time()-1);
echo '<h1>You have been succesfully logged out!</h>';
exit();
}
Once you refresh, your following condition staisfies:
if ($db_password == $password)
connection establishes, session is created and you are redirected to index.php from login.php.
Change this condtion and your script works

How to prevent browser from going back to login form page once user is logged in?

I'm trying to make a website in which the admin can upload books through an admin portal. I've made a successful login but when the user gets logged in and presses the back button (on the browser) the form page appears again, and the same happens when they log out and press back button, the page that should appear only appears after they login again. I searched a lot on the internet but all in vain. Please make a suggestion about it.
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username && $password) {
$connect = mysqli_connect("localhost", "root", "") or die ("Could'nt connect to database!"); //database connection
mysqli_select_db($connect, "mahmood_faridi") or die ("Could'nt find database");
$query = ("SELECT * FROM user WHERE username= '$username'");
$result = mysqli_query($connect, $query);
$numrows = mysqli_num_rows($result);
if ($numrows !== 0) {
while ($row = mysqli_fetch_assoc($result)) {
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($username == $dbusername && $password == $dbpassword) {
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header('location: help.php'); //another file to send request to the next page if values are correct.
exit();
} else {
echo "Password Incorrect";
}
exit();
} else {
die("That user doesn't exists!");
}
} else {
die("Please enter a username and password");
}
?>
On the login screen, in PHP, before rendering the view, you need to check if the user is already logged in, and redirect to the default page the user should see after logged in.
Similarly, on the screens requiring login, you need to check if the user is not logged in and if not, redirect them to the login screen.
// on login screen, redirect to dashboard if already logged in
if(isset($_SESSION['username'])){
header('location:dashboard.php');
}
// on all screens requiring login, redirect if NOT logged in
if(!isset($_SESSION['username'])){
header('location:login.php');
}
You can conditionally add Javascript code to go forward to the intended page.
<script>
history.forward(1);
</script>
This might be annoying or fail when Javascript is not present and/or disabled.
index.php page you should need to add the code in the top of a php file....
<?php
include 'database.php';
session_start();
if (isset($_SESSION['user_name'])) {
header('location:home');
}
if (isset($_POST['submit'])) {
$user = $_POST['user_name'];
$password = $_POST['password'];
$query = "select count(*) as count from users where user_name= '$user' and password = '$password';";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
while ($row = mysqli_fetch_assoc($result)) {
$count = $row['count'];
if ($count == 1) {
$_SESSION['user_name'] = $user;
header('location:home');
}
}
}
?>
This is another page. home.php page you should need also to add the code in the top of a php file to check it first.
<?php
include 'database.php';
if (!(isset($_SESSION['user_name']))) {
header('location:index');
}
?>
I am just modifying #sbecker's answer, use exit() after redirecting.
I have faced the same issue, but now exit(); works for me.
// on login screen, redirect to dashboard if already logged in
if(isset($_SESSION['username'])){
header('location:dashboard.php');
exit();
}
// on all screens requiring login, redirect if NOT logged in
if(!isset($_SESSION['username'])){
header('location:login.php');
exit();
}
you can use this it's easy to use
<?php
if(empty($_SESSION['user_id'])){
header("Location: login.php");
}
else{
header("Location: dashboard.php");
}
?>
My suggestion: the login should happen when the users clicks some link/button
Once the login server side takes place, use the the php function header('url') to redirect the user to the url it should be. (be careful not to echo anything otherwise the redirect will not happen)
[Edit] You say you have the first login file an html one, that is fine to me, but you say it redirects to whatever, then you are using a redirect from client side. In my opinion you should not use that client side redirect for the login. Probably that is causing the confusion.

Categories