Session does not end properly - php

So normally my session should end when I press logout button on my page but when I go to the previous page via the button (top left). I just go back to my page logged in..
This is my login page code
<?php
session_start();
$errors = array();
if(isset($_POST["name"]) and isset($_POST["password"])) {
$conn = mysqli_connect("localhost", "root", "123", "whoosh") or die("No connection made: ".mysqli_connect_error());
$name = $_POST["name"];
$password = $_POST["password"];
if (empty($name)) { array_push($errors, "Ename is required"); }
if (empty($password)) { array_push($errors, "Password is required"); }
if (count($errors) == 0) {
$query = "SELECT * FROM tbl_user WHERE name='$name' AND password='$password'";
$results = mysqli_query($conn, $query);
$user = mysqli_fetch_assoc($results);
if ($user) { // if user exists
if ($user['name'] === $name and $user['password'] === $password) {
$_SESSION['user'] = $user['id'];
header('location: mainsite.php');
}
}
}
}
?>
This is the code I put on my main site thats allows me to logout.
<?php
session_start();
if(isset($_GET['logout'])){
$_SESSION['name'] = null;
header('Location:http://leopard.med.agfa.be/leopard/website/logIn.php');
}
session_destroy();
?>
So, why is my session not working properly and doesnt log out completely?

Try this one! I dont see any where you passing name to session.
if(isset($_GET['logout'])){
// Initialize the session
session_start();
// Unset all of the session variables
session_unset();
$_SESSION = array();
// Destroy the session.
session_destroy();
unset($_SESSION['user']);
// Redirect to login page
header('Location:http://leopard.med.agfa.be/leopard/website/logIn.php');
exit();
}
Note: I used both unset() and destroy() functions you can use one.

Change the logout script to this:
<?php
if(isset($_GET['logout'])){
// null the _SESSION
$_SESSION = null;
// unset $_SESSION variable for the run-time
session_unset();
// destroy session data in storage
session_destroy();
// last, redirect
header('Location:http://leopard.med.agfa.be/leopard/website/logIn.php');
}
?>

Related

store $username and $file variables in the $_SESSION after login

From index.php I get the values of the username and password fileds with $_POST
index.php
if(isset($_POST["username"]) && isset($_POST["password"])){
$username = mysql_real_escape_string(strtolower($_POST['username']));
$password = mysql_real_escape_string($_POST['password']);
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
checkUser($_SESSION['username'], $_SESSION['password']);
}
Then I store these $username and $password variables inside the $_SESSION and call a function checkUser($_SESSION['username'], $_SESSION['password'])); which sends two parameters. The checkUser() function executes inside lib.php
lib.php
session_start();
function checkUser($username, $password){
include "connection.php";
$result = mysqli_query($conn, "SELECT * FROM `data` WHERE `username` = '$username' AND `password` = '$password'") or die("No result".mysqli_error());
$row = mysqli_fetch_array($result);
$logic = false;
if (($row['username'] == $username) && ($row['password'] == $password)) {
$logic = true;
echo "HI,".$username;
?>
<a href='logout.php'>Log Out</a>
<?php
$file = $row['file'];
echo "<img src='images/users/".$file."' >";
}
else{
echo "Failed to login. Username or password is incorrect. Try again.";
}
}
This part is for showing the name of the user and the image according to it.
logout.php works
logout.php
unset($_SESSION["username"]);
unset($_SESSION["password"]);
unset($_SESSION["file"]);
header("Location: index.php");
session_destroy();
The problem is when I navigate from one page to another, the $_SESSION variable becomes empty. Something is wrong with session. Please help me.
in the php pages you need to access session variable add session_start() after the starting <?php code

Checking user login using $_SESSIONS

Below are the following scripts, the first one is checklogin.php. This matches up the username and password that is stored in MYSQL database. Once this information has been checked they will get sent to their personal page by using a redirect function.
The bottom php script is user1's landing page. I want something on there that will confirm that this person has correctly logged in and is not entitled to view this page.
At the moment, when i log in as user1 i get shown the page 3.php, i.e. it's saying that i am not correctly logged in. I know i need to set up a session like:
$_SESSION[logged in'] == 'y';
and i think this should go where the passwords are being compared to what is stored in the database. At the moment I cannot enter my login details and be directed to the correct file at the end. Any help will be much appreciated.
<?php
session_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
mysql_connect("localhost", "root", "root") or die(mysql_error()); //Connect to server
mysql_select_db("first_db") or die("Cannot connect to database"); //Connect to database
$query = mysql_query("SELECT * from users WHERE username='$username'"); //Query the users table if there are matching rows equal to $username
$exists = mysql_num_rows($query); //Checks if username exists
$table_users = "";
$table_password = "";
if ($exists > 0) {
//IF there are no returning rows or no existing username
//$_SESSION['logged in'] == 'y';
while ($row = mysql_fetch_assoc($query)) {
//display all rows from query
$table_users = $row['username']; // the first username row is passed on to $table_users, and so on until the query is finished
$table_password = $row['password']; // the first password row is passed on to $table_users, and so on until the query is finished
$table_id = $row['id'];
$page_id = $row['page'];
}
if (($username == $table_users) && ($password == $table_password)) {
// checks if there are any matching fields
if ($password == $table_password) {
$_SESSION['user'] = $username; //set the username in a session. This serves as a global variable
$_SESSION['logged_in'] = 'y';
//echo $table_id;
//echo $page_id;
redirect($page_id); //take the user to the page specified in the users table
} else {
echo "Login Failed";
}
} else {
print '<script>alert("1. Incorrect Password!");</script>'; //Prompts the user
print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
} else {
print '<script>alert("Incorrect Username!");</script>'; //Prompts the user
print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
function redirect($page_id)
{
/* Redirect browser */
header('Location: '.$page_id);
/* Make sure that code below does not get executed when we redirect. */
exit;
}
?>
And landing page
<?php
session_start();
//user logged in??
if ($_session['logged in'] != 'Y') {
//No- jump to log in page.
header("location: 3.php");
exit();
}
else
{
echo 'this works';
}
?>
You're defining the session like:
$_SESSION['logged in'] == 'y';
which should be:
$_SESSION['logged in'] = 'y';
yet you check like:
if ($_session['logged in'] != 'Y') {
it should be:
if ($_SESSION['logged in'] != 'y') {
You're checking if it's an uppercase Y while it holds a lowercase y. So it will never succeed.
Also $_SESSION is a superglobal which means:
Superglobals — Superglobals are built-in variables that are always
available in all scopes
and variables are case sensitive.

Login Not Working PHP MySQL

I'm trying to fix my login page...
It works fine on the login.php with redirecting but on the index it doesn't redirect even if the session is empty. Any pointers? I'm new to this, so forgive me if it's really obvious.
<?php
require_once('../includes/config.php');
session_start();
if(!isset($_SESSION['loggedin']) && $_SESSION['loggedin']=='no'){
// not logged in
header("location: login.php");
exit();
} else {
$_SESSION['loggedin'] = 'yes';
}
?>
<?php
include("../includes/config.php");
$error = NULL;
$atmpt = 1;
if (!isset($_SESSION)) {
session_start();
}
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin']=='yes'){
// logged in
header("location: index.php");
exit();
}
if(isset($_POST['login']))
{
/* get username and password */
$username = $_POST["username"];
$password = $_POST["password"];
/* MySQL Injection prevention */
$username = mysqli_real_escape_string($mysqli, stripslashes($username));
$password = mysqli_real_escape_string($mysqli, stripslashes($password));
/* check for user in database */
$query = "SELECT * FROM admin_accounts WHERE username = '$username' AND password = '$password'"; // replace "users" with your table name
$result = mysqli_query($mysqli, $query);
$count = $result->num_rows;
if($count > 0){
//successfully logged in
$_SESSION['username']=$username;
$_SESSION['loggedin']='yes';
$error .= "<div class='alert alert-success'>Thanks for logging in! Redirecting you..</div>";
header("refresh:1;url=index.php");
} else {
// Login Failed
$error .= "<div class='alert alert-danger'>Wrong username or password..</div>";
$_SESSION['loggedin']='no';
$atmpt = 2;
}
}
?>
The line
session_start();
should be the very first line in the php script.
Just modify first three lines.
As session_start() should be put before any output has been put on the browser (even space).
<?php
session_start();
require_once('../includes/config.php');
if (empty($_SESSION['loggedin']) && $_SESSION['loggedin']=='no') {
...

Is $_SERVER[HTTP_HOST] the cause of redirect issues?

I have enabled vanity urls (user.domain.com). When a session expires or somebody clears the cookies, the page would get redirected to user.domain.com which has the login page. So, on all pages i am using the following code:
if(!isset($_SESSION['user_name'])) { header("Location: http://$_SERVER[HTTP_HOST]");}
2 of of 10 times i get a redirect error saying that the page is redirecting too many times.
Could this be the reason? And if it is what can i do to redirect in a way that won't cause such issues.
Thanks.
Login code:
<?php
session_start();
// Process the POST variables
$username = $_SESSION["user_name"];
//$password = $_POST["password"];
// Set up the session variables
$_SESSION["user_name"] = $username;
$ugData = $_REQUEST['sub_name'];
if($_POST){
$_SESSION['user_name']=$_POST["user_name"];
$_SESSION['password']=$_POST["password"];
}
$secret = $info['password'];
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site']))
//if there is, it logs you in and directes you to the members page
{
$username = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$check = mysql_query("SELECT user_name, password FROM accounts WHERE user_name = '$username' and sub_name='$ugData'")or die(mysql_error());
while($info = mysql_fetch_array( $check ))
{
if (# $info['password'] != $pass)
{
}
else
{
header("Location: home.php");
}
}
}
//if the login form is submitted
if (isset($_POST['submit'])) { // if form has been submitted
// makes sure they filled it in
if(!$_POST['user_name'] | !$_POST['password']) {
die('You did not fill in a required field.');
}
// checks it against the database
if (!get_magic_quotes_gpc()) {
$_POST['user_name'] = addslashes($_POST['user_name']);
}
$check = mysql_query("SELECT user_name,password FROM accounts
WHERE user_name = '".$_POST['user_name']."'
and sub_name='".$ugData."'")or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
die('That user does not exist in our database.
<a href=add.php>Click Here to Register</a>');
}
while($info = mysql_fetch_array( $check ))
{
$_POST['password'] = md5($_POST['password']);
$_POST['password'] = $_POST['password'];
//gives error if the password is wrong
if (# $_POST['password'] != $info['password']) {
die('Incorrect password, please try again');
}
else
{
// if login is ok then we add a cookie
$_POST['user_name'] = stripslashes($_POST['user_name']);
$hour = time() + 3600;
setcookie(ID_my_site, $_POST['user_name'], $hour);
setcookie(Key_my_site, $_POST['password'], $hour);
//then redirect them to the members area
header("Location: home.php");
}
}
}
else
{
?>
The header("Location: http://{$_SERVER['HTTP_HOST']}"); isn't the problem per-say.
However, if you do have that code on your login page then yes, you'll just keep redirecting yourself to the home page because you won't be able to login.
Make sure that you do not redirect the user if he's on the login page.
EDIT: Try header('Location: /'); Maybe you have some weird server issue which causes $_SERVER['HTTP_HOST'] do sometimes be null.
Assuming that redirecting to http://yourserver/ means http://yourserver/index.php, then you should change the if to read
if(!isset($_SESSION['user_name']) && $_SERVER['PHP_SELF'] != '/index.php')
{
header("Location: http://$_SERVER[HTTP_HOST]");
}
This will avoid endless redirects.
Try using this with a die():
if(!isset($_SESSION['user_name'])) { header("Location: http://user.domain.com"); die();}
If url changes from user to user grab username from db first, and use it in redirection. Try something like:
...
$username = $row["username"];
...
and use it:
if(!isset($_SESSION['user_name'])) { header("Location: http://".$username.".domain.com"); die();}

php sessions to authenticate user on login form

I have the following code designed to begin a session and store username/password data, and if nothing is submitted, or no session data stored, redirect to a fail page.
session_start();
if(isset($_POST['username']) || isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
$navbar = "1";
$logindisplay = "0";
$username = $_SESSION['username'];
$password = $_SESSION['password'];
} else {
header('Location:http://website.com/fail.php');
}
$authed = auth($username, $password);
if( $authed == "0" ){
header('Location:http://website.com/fail.php');
}
Its not working the way it should and is redirecting me to fail even though i submitted my info and stored it in the session. Am i doing something wrong?
NOTE the authed function worked fine before i added the session code.
what about using this to setup session
session_start();
if( isset($_POST['username']) && isset($_POST['password']) )
{
if( auth($_POST['username'], $_POST['password']) )
{
// auth okay, setup session
$_SESSION['user'] = $_POST['username'];
// redirect to required page
header( "Location: index.php" );
} else {
// didn't auth go back to loginform
header( "Location: loginform.html" );
}
} else {
// username and password not given so go back to login
header( "Location: loginform.html" );
}
and at the top of each "secure" page use this code:
session_start();
session_regenerate_id();
if(!isset($_SESSION['user'])) // if there is no valid session
{
header("Location: loginform.html");
}
this keeps a very small amount of code at the top of each page instead of running the full auth at the top of every page. To logout of the session:
session_start();
unset($_SESSION['user']);
session_destroy();
header("Location: loginform.html");
First, don't store the password in the session. It's a bad thing. Second, don't store the username in the session until after you have authenticated.
Try the following:
<?php
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$authed = auth($username, $password);
if (! $authed) {
header('Location: http://website.com/fail.php');
} else {
$_SESSION['username'] = $username;
}
}
if (isset($_SESSION['username'])) {
$navbar = 1;
$logindisplay = 0;
} else {
header ('Location: http://website.com/fail.php');
}
Just some random points, even though they may not actually pertain to the problem:
Don't store the password in plaintext in the session. Only evaluate if the password is okay, then store loggedIn = true or something like that in the session.
Check if the password and the username are $_POSTed, not || (or).
Don't pass password and username back and forth between $password and $_SESSION['password']. Decide on one place to keep the data and leave it there.
Did you check if you can store anything at all in the session? Cookies okay etc...?
To greatly simplify your code, isn't this all you need to do?
if (isset($_POST['username'] && isset($_POST['password'])) {
if (auth($_POST['username'], $_POST['password'])) {
$_SESSION['user'] = /* userid or name or token or something */;
header(/* to next page */);
} else {
// display "User credentials incorrect", stay on login form
}
} else {
// optionally: display "please fill out all fields"
}
Here are a few other things, which may or may not help you, by the way :
Do you have error_reporting on ? (see also)
Do you have display_errors on ?
Is session_start the first thing you are doing in your page ? There must be nothing output before
Are the cookies created on the client-side ?
header Location indicates the browser it has to go to another page ; it doesn't stop the execution of the PHP script. You might want to (almost always anyway) add "exit" after it.
Headers are not function calls. They put a directive into the HTTP headers, and the last one to execute is the one which will be processed. So let say if you have something like this
if ($bAuthed)
{
header("location: login.php");
}
// error case
header("location: error-login.php");
You will always be redirected to error-login.php no matter what happens. Headers are not function calls!
The solution to my specific problem above
session_start();
if(isset($_POST['username']) || isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
$navbar = "1";
$logindisplay = "0";
$username = $_SESSION['username'];
$password = $_SESSION['password'];
$authed = auth($username, $password);
if( $authed == "0" ){
header('Location:http://website.com/fail.php');
}
} else {
header('Location:http://website.com/fail.php');
}
Don't use else section in second if statement.
session_start();
if(isset($_POST['username']) || isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
$navbar = "1";
$logindisplay = "0";
$username = $_SESSION['username'];
$password = $_SESSION['password'];
}
$authed = auth($username, $password);
if( $authed == "0" ){
header('Location:http://website.com/fail.php');
}

Categories