The corret session declaration - php

I am just confused with the session in the login configuration.
For example:
if($ensure_credentials) {
$_SESSION['status'] = 'authorized';
$_SESSION['username'] = $username; /* save the users username to session */
header("location: index.php");
} else return "Please enter a correct username and password";
In there it is declared if the login success so that the session status is authorized. But why in the index page it is declared like this:
session_start();
if($_SESSION['status'] !='authorized') header("location: login.php");
Which it means that if the session status is authorized than it will be directed to login page.
I have to ask this question because it always direct me back to login page.

Anytime you are going to write to a PHP session or read from it you need to make sure a session is started. To do this you can use the following code:
if( !isset( $_SESSION ) ){
session_start();
}
To find out what your session currently holds you can do a:
print_r( $_SESSION );
This will tell you what is currently stored within your active session.
Then you do:
if( $ensure_credentials) {
$_SESSION['status'] = 'authorized';
$_SESSION['username'] = $username;
header("location: index.php");
}
if( $_SESSION['status'] !== 'authorized' ){
header("location: login.php");
}

Related

How to destroy current session but not other session

I have a simple log in system where there are 2 type of user (role: 0,1). If user is role 0 then user is redirected to search.php, else role is 1,redirected to overview.php.
if ($role == 0){
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['email'];
$_SESSION['id'] = $id;
header('Location: search.php');
} elseif ($role == 1) {
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['user'] = $name;
$_SESSION['name'] = $_POST['email'];
$_SESSION['id'] = $id;
header('Location: overview.php');
}
I am able to logout and destroy session, but if both user are logged in and one user logout it will end session for both user.
Here is my logout.php:
<?php
// Initialize the session
session_start();
// Destroy the session.
session_destroy();
header('Location: login.php');
exit;
?>
Then I found this solution source. I was not sure how to get to_destroy_id ($des) so I set it to current session id.
Here is my updated logout.php:
<?php
$des = session_id();
// 1. commit session if it's started.
if (session_id()) {
session_commit();
}
// 2. store current session id
session_start();
$current_session_id = session_id();
session_commit();
// 3. hijack then destroy session specified.
session_id($des);
session_start();
session_destroy();
session_commit();
// 4. restore current session id. If don't restore it, your current session will refer to the session you just destroyed!
session_id($current_session_id);
session_start();
session_commit();
// Redirect to the login page:
header('Location: restTablet.php');
?>
This worked for first time then it stopped working again. Everyone logout if one user logout.
I would just like to destroy user session if they clicked logout, and other users stays logged in. Any idea how can I implement this?
UPDATE: making the following change to logout.php I was able to keep other logged in if one user logout, but once the user logout and tries to go back user is able to access it again without loggin. Here is the logout.php:
<?php
$des = session_id();
// 1. commit session if it's started.
if (session_id()) {
session_commit();
}
// 2. store current session id
session_start();
$current_session_id = session_id();
session_commit();
// 3. hijack then destroy session specified.
session_id($des);
session_start();
session_destroy();
session_commit();
// Redirect to the login page:
header('Location: gabLogin.php');
?>
You can nest your $_SESSION data in a parent level.
For example you have two roles, role 1 and role 2.
Set $_SESSION like the following:
if ($role == 0){
session_regenerate_id();
$_SESSION['role_0']['loggedin'] = TRUE;
$_SESSION['role_0']['name'] = $_POST['email'];
$_SESSION['role_0']['id'] = $id;
header('Location: search.php');
} elseif ($role == 1) {
session_regenerate_id();
$_SESSION['role_1']['loggedin'] = TRUE;
$_SESSION['role_1']['user'] = $name;
$_SESSION['role_1']['name'] = $_POST['email'];
$_SESSION['role_1']['id'] = $id;
header('Location: overview.php');
}
Then when your user logs out of say role_0, unset only the parent session value for that role.
//use logic in logout form to POST proper logout for that role.
if(isset($_POST['logout_0'])){ //--> role_0 is logging out
unset($_SESSION['role_0']); //--> all child data for role_0 should be unset now.
//--> check if user is logged in as alternate role
if($_SESSION['role_1']['loggedin'] === TRUE){
header('Location: overview.php');
}else{
//--> redirect to the page you wish them to go to when logged out
}
}

Php - Prevent a User from Accessing a Page when He/She Typed the URL [duplicate]

In attempt of securing an administrator area of a site I'm working on I made an index.php which contains
if (isset($_POST['password']) && isset($_POST['userName'])) {
if($_POST['password']==$pass && $_POST['userName']==$username)
{
header( 'Location: admin.php' ) ;
}
This redirects to a file in the same folder called admin.php. The problem is that I can access this file if I write localhost/folder/admin.php. Please tell me how to restrict the direct access to this page. The only way accesing it should be from index.php after username and password.
set a session variable and check it everytimes somebody access admin.php
<?php
if (isset($_POST['password']) && isset($_POST['userName'])) {
if ($_POST['password'] == $pass && $_POST['userName'] == $username) {
if (!session_id())
session_start();
$_SESSION['logon'] = true;
header('Location: admin.php');
die();
}
?>
and
//admin.php
if (!session_id()) session_start();
if (!$_SESSION['logon']){
header("Location:index.php");
die();
}
You should look into PHP sessions. You can set a session variable "isLogged" in that redirection file, and then check in admin.php if that session variable is registered, if not redirect to the login page!
session_start();
if (isset($_POST['password']) && isset($_POST['userName'])) {
if($_POST['password']==$pass && $_POST['userName']==$username)
{
header( 'Location: admin.php' ) ;
$_SESSION['isLogged'] = true;
}
admin.php
session_start();
if(!$_SESSION['isLogged']) {
header("location:login.php");
die();
}
Note: session_start(); must be called before the $_SESSION global can be utilised.
Set a session value that signifies that a user has successfully logged in, check for it on every page you want secured, redirect to login if that value isn't set.

How to fix failed redirects after login in PHP

I added login to my site, everything works except one thing: if a user who is not logged in is not redirected to login.php, I tried several things please help me, Thanks.
process.php (login process):
if ($row['username'] == $username && $row['password'] == $password && ("" !== $username || "" !== $password)){
$_SESSION["users"] = $row['username'];
$_SESSION['login'] = true;
header("Location: https://**********/inde.php");
} else {
header("Location: error.php");
}
logout.php:
session_start();
$_SESSION['users'] = NULL;
$_SESSION['login'] = false;
header("location: https://**********/login.php");
exit();
On all pages of the website I added:
include("content/login_verif.php");
login_verif.php:
session_start();
if $_SESSION['login'] != true;
{
header('Location: https://**********/login.php');
exit();
}
Simply put a safeguard in your home page. Check whether both $_SESSION['users'] and $_SESSION['login'] is set or not. If either of them is not set, then redirect the user to login page.
login_verif.php
session_start();
if(!isset($_SESSION['users']) || !isset($_SESSION['login'])){
// redirect the user to login page
header('Location: https://ferapps.altervista.org/tia/content/login/login.php');
exit();
}
and include this login_verif.php page in the following way,
require_once("content/login_verif.php");
And that's not how you should logout a user. You need to properly clear the cookies and destroy the sessions, so your logout.php page should be like this:
logout.php
<?php
session_start();
if(!isset($_SESSION['users']) || !isset($_SESSION['login'])){
// redirect the user to login page
header('Location: https://ferapps.altervista.org/tia/content/login/login.php');
exit();
}
$_SESSION = array();
if(isset($_COOKIE[session_name()])){
setcookie(session_name(),'',time()-42000,'/');
}
session_destroy();
// redirect the user to login page
header('Location: https://ferapps.altervista.org/tia/content/login/login.php');
exit();
?>
The issue here is the incorrect use of "file_get_contents".
file_get_contents as explained at http://php.net/manual/en/function.file-get-contents.php is a way to fetch the content of another file and return it in a string format.
If you wanna extend a file with another files code you should look into require and/or include.
For your current code, swap out
file_get_contents("content/login_verif.php");
For
require("content/login_verif.php");
Information regarding include: http://php.net/manual/en/function.include.php
Information regarding require: http://php.net/manual/en/function.require.php
file_get_contents()
is used to output the contents of a file as a string.
You want
include("content/login_verif.php");
instead. And
if $_SESSION['login'] != true;
should be
if ($_SESSION['login'] != true)

verifying two session variable upon log in

I have to pages that requires login. admin.php and rehab.php. upon login i set two session variable:
if($row[2]=='Admin'){
// Initializing Session
session_start();
$_SESSION['user']=$username; // Initializing Session user
$_SESSION['dept']='Admin'; // Initializing Session dept.
header('location: admin.php');
}
else if($row[2]=='Rehabilitation Services'){
$_SESSION['user']=$username; // Initializing Session
$_SESSION['dept']='Rehabilitation Services';
header('location: rehab.php');
}
This both pages have include header.php (where username can be seen). I've decided to put the session validation in header.php:
session_start();
if (!(isset($_SESSION['user']) && $_SESSION['user'] != '')) {
header ("Location: login.php");
}
so whenever someone will access admin page by typing in in the browser (../admin.php) or (../rehab.php) it will be re-directed to the login page.
My problem is, if a REHAB user is now logged on. (../rehab.php) whenever i try to change rehab.php to admin.php IT CAN STILL BE ACCESSED! i try putting this in the top of admin.php but it doesn't seem to work.
if ((isset($_SESSION['dept'])) && $_SESSION['dept']!='Admin'){
session_destroy();
}
In the rehab.php page, if you want to restrict access only to those who are logged in and have a 'Rehabilitation Services' dept assigned, you should use:
session_start();
if(!isset($_SESSION['user']) ||
(isset($_SESSION['dept']) && $_SESSION['dept']!='Rehabilitation Services')){
header ("Location: login.php");
}
This should work; there are couple of things I've noticed and you're code structure is good as far as what you're trying to accomplish:
session_start(); // Have this as the first thing on the script
// at the top before anything else above it
if($row[2]=='Admin'){
// Initializing Session
session_start(); // Remove this; you need to put session_start
// at the top of the script
$_SESSION['user'] = $username; // Is the $username coming in
// from $_POST? Should this be
// $_POST['username'] unless you
// defined it beforehand
$_SESSION['dept'] = "Admin"; // Initializing Session dept.
// This is ok.
header('location: admin.php');
} elseif($row[2] == "Rehabilitation Services"){ //Keep this in one line
$_SESSION['user'] = $username; // Initializing Session
$_SESSION['dept'] = "Rehabilitation Services";
header('location: rehab.php');
}
session_start();
if (!(isset($_SESSION['user']) && $_SESSION['user'] != '')) {
if (!isset($_SESSION['user']) && $_SESSION['user'] != '') {
// corrected line above, you can also use empty() function
header ("Location: login.php");
}
if ((isset($_SESSION['dept'])) && $_SESSION['dept']!='Admin'){
if (isset($_SESSION['dept']) && $_SESSION['dept'] != 'Admin'){
//Corrected line above
session_destroy();
}

if is not session , redirect to login page

I am trying to code a simple script,
I created a " ADMIN Panel " , so if the user is admin (admin=1) then he can pass and see the link/file
If he is not (admin=0) then he should be redirected to login page , and if is not Session['username'] he should go back to login page ,
but it seems that i have a problem with this code, in user panel it works , but in admin panel it doesn't
<?php
include './includes/db.php';
session_start();
// ADMIN CHECk
$username = mysql_real_escape_string($_SESSION['username']);
$result = mysql_query("SELECT * FROM users WHERE username='$username' AND admin=1");
$count = mysql_num_rows($result);
if($count != 1) // make sure user is a admin
{
session_start();
session_destroy();
header("location: login.php");
die;
}
if(isset($_GET['act']))
{
if($_GET['act'] == "logout")
{
session_start();
session_destroy();
header("location: login.php");
}
}
?>
Ok, first thing i see is that you don't declare the session first. Secondly, the mysql function is deprecated, mysqli will do what you need done. This fix should work for you. Also it would be easier to have a logout.php.
db.php
<?php
$db = new mysqli(host, user, pass, database);
?>
Then, in your page, you can run the queries like so:
<?php
session_start();
include './includes/db.php';
//check that the session exists
if(!isset($_SESSION['username'])
{
//the session does not exist, redirect
header("location: login.php");
}
// ADMIN CHECk
$username = $db->real_escape_string($_SESSION['username']);
$result = $db->query("SELECT * FROM users WHERE username='$username' AND admin='1'");
$count = $result->num_rows;
if($count != 1) // make sure user is a admin
{
header("location: login.php");
}
?>
Then in logout.php, you should remember to actually unset the session variables
<?php
session_start();
//unset session variables
unset($_SESSION['username']);
session_destroy();
header("location: login.php");
?>

Categories