User authentication Session is set from the start - php

I'm working on page authentication. It can login already, but I want it to make user authentication on other pages aswell if someone tries to access pages through URL. If the person is not a logged in user, redirect that person to the login page. I tried it by working with sessions but it doesn't work. I'm following MVC structure
Somehow the sessions never gets unset. I don't know why..
Here is how I did it
My loginController
<?php
//LoginController
if($_POST)
{
if(isset($_POST['submit']) AND $_POST['submit'] == "login")
{
$username = $_POST['username'];
$password = $_POST['password'];
try
{
include '../model/Login.php';
$login = new Login($db, $username, $password);
if($login == TRUE)
{
session_start();
$_SESSION['username'] = $username;
header("Location:../index.php");
}
}
catch (Exception $exc)
{
echo $exc->getMessage();
}
}
}
My index controller( for main page)
<?php
include 'model/Database.php';
session_start();
//Checks if the user is logged in.
if(!isset($_SESSION['username'])) {
//echo"<h2>You have no access to this page!";
include 'view/login.php';
die();
}
include 'c:/wamp/www/mvc/model/Display.php';
$displayPatients = new Display($db);
$dataDisplay = $displayPatients->getData();
include 'view/Main.php';
?>
my logout.php: When a user clicks this button:
<?php
//Logout
//destroys the session when the user clicks logout
session_destroy();
header('Location:view/login.php'); //redirect to the login
The user does get logged out redirected to the login page but the session is still set. The session is set from the beginning and I have no idea why..

Just taken out of the manual for the session_destroy()
session_destroy() destroys all of the data associated with the current
session. It does not unset any of the global variables associated with
the session, or unset the session cookie. To use the session variables
again, session_start() has to be called.
In order to kill the session altogether, like to log the user out, the
session id must also be unset. If a cookie is used to propagate the
session id (default behavior), then the session cookie must be
deleted. setcookie() may be used for that.
So it seems to me you need to destroy your session id or set it to something else when starting the new session otherwise your next sesson_start() resumes the old session again.
For this reason you could also just regenerate the session id on login before redirecting. Ah and it's always a good idea to use "exit;" after a "Location:" redirect via "header()".
session_start();
session_regenerate_id(true);

Related

Logout from secure single page with php sessions

I'm securing single page with session:
if($username === 'admin' && $password === 'admin1'){
$_SESSION['secured'] = "Secured";
header('LOCATION:admin/approve.php'); //go to location after successful login.
die();
}
In approve page I'm checking if session is set:
session_start(); //starting session to acces to it
if(!isset($_SESSION['secured'])){
exit();
}
I made a logout button that redirect to site index, but after logout when I'm tring to reach the secure page i dont have problem to enter, and session is still set.
Logout code:
unset($_SESSION); //clear session array
session_destroy(); //Destroy session
unset($_SESSION['secured']);
header("Location: ../index.html");
You mean the approve page?
What I see is that you did not specify where the page should exit to...
Maybe you should try something like this:
session_start(); //starting session to acces to it
if(!isset($_SESSION['secured'])){
header("Location: ../index.html");
exit();
}
I hope it helps

Session reset without session_destroy is valid?

I'm trying to destroy the session without using session_destroy because I want to carry the information message. My question is if my code is valid, I already reset the session by saying all $_SESSION is an empty array or for security reason using the session_destroy is a must but if I use session_destoy I can't pass the $_SESSION['msg'] anymore.
<?
session_start();
$_SESSION = array();
//session_destoy();
$_SESSION['msg'] = "You have logged out.";
header('Location: index.php');
?>
You need session_unset()
session_unset just clears out the session for usage. The session is
still on the users computer. Note that by using session_unset, the
variable still exists. session_unset just remove all session
variables. it does not destroy the session....so the session would
still be active.
via: http://php.net/manual/en/function.session-unset.php
and then you can do it like
$_SESSION['msg'] = "You have logged out.";
so that the msg is added to session.
OR You can do it like this too:
$msg ="Whatever the message is";
header("Location: index.php?message=$msg ");
In index.php file
if(isset($_GET['message']) && !empty($_GET['message'])){
echo $_GET['message'];
}
1st you should use session_unset(); to remove all session variables/values rather than assigning a new array to it.
The main answer to your query:
I would recommend to use session_destroy() because it removes the internal session ID generated which would be validated at every request coming from a client device. To verify this, just print the session ID using the function echo session_id(); before and after emptying the session in the way you are doing. It would pring the same session ID.
So destroying it first and then creating new will be a good idea.
Once you destroy the session using session_destroy() you can start a new session again and set your message $_SESSION['msg'] in it.
Just user session_unset($_SESSION['session_name']); hope this will work.
You can use cookies; you would keep for example the username, the password and the connection status of the user. When the user comes back to your site, you know who he is and if he is already connected.
setcookie ("Msg", "you have logged out", time () + 3600);
(for a cookie of one hour, you put the time that you want ...)
Your code:
<?
session_start();
$_SESSION = array();
//session_destoy();
$_SESSION['msg'] = "You have logged out.";
header('Location: index.php');
?>
in the index page do below stuff:
<?php
if(!empty($_SESSION['msg']) && isset($_SESSION['msg'])){
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
?>
this will show your message once and unset it immediately.

PHP session_destroy() isn't working

This is frustrating, I've been working with PHP Sessions for a long time and haven't had this problem until now. I'm working on a basic login/logout script using PHP.
Here's what I have for my logout script.
logout.php
<?php
session_start();
unset($_SESSION['email']);
session_destroy();
header("Location:login.php");
?>
And therefore my login.php script has the following code:
login.php
// I send the user to logged_in.php if the session already exists.
if(isset($_SESSION['email'])) header("Location:logged_in.php");
if(pass and username are correct){
$_SESSION['email'] = $email;
session_write_close();
header('Refresh: 1; logged_in.php');
}
Now when I login and I'm redirected to logged_in.php page, form there when I go to logout.php page, instead of being redirected to login.php it goes back to logged_in.php.
Which means that when it arrives to login.php the session still exists and it enters the following if statement in login.php
if(isset($_SESSION['email'])) header("Location:logged_in.php);
Try something like that:
session_start();
// I send the user to logged_in.php if the session already exists.
if(isset($_SESSION['email'])) header("Location:logged_in.php");
if(pass and username are correct){
$_SESSION['email'] = $email;
session_write_close();
header('Refresh: 1; logged_in.php');
}
session_regenerate_id(true) worked for me. I was having the same issue before. It appears that some browsers do not properly delete the session cookie while they are active. Regenerating the ID gives you a fresh session, though you should still of course delete your old session as you have. I'm not quite sure if this is a fix or a workaround, but it works. session_regenerate_id will create a new session variable and delete the old one if you set the parameter to true.

PHP Cookies not being loaded when coming from a clicked link

I'm working on a website that is keeping a user session token in $_SESSION. When I type the URL directly, I can load the cookies just fine, but when I click on a page that loads the cookie through PHP, it can't find the cookie. Is there any way to get around this?
Here's the code for saving the cookie
setcookie("tpl_token", $token, time()+365*24*60*60, "/");
And for retrieving
if(isset($_COOKIE['tpl_token'])){
$token = $_COOKIE['tpl_token'];
} else {
echo "Cookie not set";
}
It is returning that cookie is not set.
In order to create a session in PHP, use the session_start() function. PHP handles sessions internally for you, so you do not have to do any dirty work.
Example:
session_name("tpl_token");
session_start(); //sends session cookie with name "tpl_token"
//create session variable.
$_SESSION["logged_in"] = true;
if(isset($_SESSION["logged_in"])){
//stuff to do if user is logged in already
} else {
//stuff to do if user is not logged in.
}
//Destroy Session/Logout;
session_unset();
session_destroy();
If you are try create session cookies, there is no need for the $_COOKIE[] function

How to secure my PHP webpage from unauthorized Users

I am new in PHP and facing a problem with security.
I use this to redirect unauthorized users if they not logged in.
<?php
session_start();
if(!isset($_SESSION['user_id'])) {
header('Location: login.php');
}
?>
It is on every top of my page but when I log in and click my protected page it will redirect to login page instead of original/protected page open and my session variable is set on my login page how to include this session variable in my protected page from login page.
If when, you log in, it sends you to login page, then $_SESSION['user_id'] may not be set, or you aren't including session in your file, to check it, do:
var_dump($_SESSION['user_id'])
on the page, and temporally leave out the header if the var_dump returns NULL, it means, $_SESSION['user_id'] is not set
Try this:
if(!isset($_SESSION['user_id']))
{
// The user id variable is not set. Therefore, the user is most likely a guest.
$_SESSION['user_id'] == 0;
}
if($_SESSION['user_id'] == 0)
{
// The user does not have a user id set. We assume, therefore, that they are a guest.
header("Location: login.php");
}
Also, in your login script, ensure that you are setting $_SESSION['user_id'] to anything other than 0.

Categories