Storing users sessions - php

I have a login and signup page, actually i want to store users sessions when they click logout button,they are not allowed to enter the home page until they enter their user name and password..!
On the login page i have the code for storing the session.
$user_name = $_SESSION['user_name'] = $_POST['user_name'];
And on the home page i have the condition..
<?php
session_start();
if(!$_SESSION['user_name']==1){
header("location:login.php?error=You must be logged in first!");
exit();
}
?>
The main issue is that when user clicks logout and redirects to the login page ..if he type the home page URL in the addressbar..he reaches the home page without entering the passsword and login..What's the problem..

Try this
login.php
<?php
session_start();
// Log in on submit
if (isset($_POST['user_name']) /* whatever */) {
// Do some login validations here
// and if successful, set the session then redirect
$_SESSION['sess_user'] = $_POST['user_name'];
header('Location: /members.php');
exit();
}
?>
logout.php
<?php
session_start();
// Unset all session values
$_SESSION = array();
// get session parameters
$params = session_get_cookie_params();
// Delete the actual cookie.
setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
// Destroy the session
session_destroy();
header("Location: /login.php");
?>
members.php
<?php
session_start();
// Check if authenticated
if (!isset($_SESSION['sess_user'])) {
header("location:login.php?error=You must be logged in first!");
exit();
}
?>

Related

Users getting logged out after a short amount of time

I am having some issue with session. The users gets logged out after a short amount of time. I have read some tutorials and a few questions/answers here on SO, but I can't seems to find the issue.
This is on the top of login.php:
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["isloggedin"]) && $_SESSION["isloggedin"] === true){
header("location: index.php");
exit;
}
This is the code I run when the user has successfully logged in:
session_start();
session_regenerate_id();
ini_set('session.gc_maxlifetime', 3600); // Make session last for 1 hour before user has to login again
session_set_cookie_params(3600); // Make session last for 1 hour before user has to login again
$_SESSION["isloggedin"] = true;
$_SESSION["team"] = $currentTeam;
This is the code I have in top of all pages on my website:
<?php
session_start();
if (!isset($_SESSION['isloggedin'])) { // If not logged in, redirect to login page
header('Location: login.php');
exit;
}
$team = $_SESSION["team"];
?>
What am I doing wrong here?

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
}
}

Preventing a user to stop accessing another user page on the same browser in different tab without logging in using session variable PHP

Suppose, I have a login page located at https://www.example.com/a/login.php. After successful login, user redirects to https://www.example.com/a/admin.php. I have another login page located at https://www.example.com/b/login.php and after successful login user redirects to https://www.example.com/b/admin.php. Now suppose, In a browser, a user successfully logs in to https://www.example.com/a/login.php. and redirects to admin.php page. If another user tries to access the page https://www.example.com/b/admin.php directly without login page in the same browser in another tab, then he easily bypasses the login and reaches the admin.php page. My sample code is :
login.php
<?php
session_start();
// if user successful login
$_SESSION['user_id'] = $users_id
// we redirect user to member page
if (isset($_SESSION['user_id']){
header("Location:admin.php");
}else{
header("Location:login.php");
}
?>
admin.php
<?php
session_start();
if (!isset($_SESSION['user_id']){
header("Location:login.php");
}
echo "welcom user : {$_SESSION['user_id']}";
?>
Is there any way so that if the second user tries to access https://www.example.com/b/admin.php, in another tab of same browser, then he will be redirect to https://www.example.com/b/login.php ?
Try setting another $_SESSION variable..
So like this:
<?php
session_start();
// if user successful login
$_SESSION['user_id'] = $users_id
$_SESSION['url'] = "a"; // a if https://www.example.com/a/login.php, b if https://www.example.com/b/login.php
// we redirect user to member page
if (isset($_SESSION['user_id']){
header("Location:admin.php");
}else{
header("Location:login.php");
}
?>
And at your https://www.example.com/a/admin.php , you should set it like this;
<?php
session_start();
if (!isset($_SESSION['user_id'])){
header("Location:login.php");
}
elseif (!isset($_SESSION['url'])){
header("Location:login.php");
}
elseif ($_SESSION['url'] != "a"){
header("Location:login.php");
}
echo "welcome user : {$_SESSION['user_id']}";
?>
And then at your https://www.example.com/b/admin.php , you should set it like this;
<?php
session_start();
if (!isset($_SESSION['user_id'])){
header("Location:login.php");
}
elseif (!isset($_SESSION['url'])){
header("Location:login.php");
}
elseif ($_SESSION['url'] != "b"){
header("Location:login.php");
}
echo "welcome user : {$_SESSION['user_id']}";
?>
Hope this helps you!

Php login system suddenly stopped working

I built a PHP/MySql login system for a website I am working on and all was working fine. I took a month off from working on it, pulled it up last night, and all of a sudden it doesn't work. It recognizes if a wrong username or password was entered, but if you enter the correct information it redirects you to the login page again. Was there some update somewhere that I am unaware of? I did not change anything in any of my files. It was working perfectly a month ago, and with no change at all it doesn't work now. Any ideas?
UPDATE
It is working if I check the remember me box, but not if I don't I will paste my code below:
Login Script:
<?php
define('INCLUDE_CHECK',true);
require 'connect.php';
require 'functions.php';
session_name('TheLoginSession');
session_start();
// ---------- LOGIN ----------
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['remembercheck'] = (int)$_POST['remembercheck'];
$storedsaltquery = mysql_fetch_assoc(mysql_query("SELECT rand FROM members WHERE usr = '".$_POST['username']."'"));
$storedsalt = $storedsaltquery['rand'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,compid,usr,firstName,level,yn FROM members WHERE usr='{$_POST['usernamelog']}' AND pass='".hash("sha256",$_POST['passwordlog'].$storedsalt)."'"));
if($row['id'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['comp']=$row['compid'];
$_SESSION['id'] = $row['id'];
$_SESSION['name'] = $row['firstName'];
$_SESSION['usrlevel'] = $row['level'];
$_SESSION['new'] = $row['yn'];
$_SESSION['remembercheck'] = $_POST['remembercheck'];
// Store some data in the session
setcookie('Remember','remembercheck',time()+1209600,'/','.domain.com');
}
else $err[]='Wrong username and/or password!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
echo header("Location: ../index.php");
exit;
}
Index Page:
<?php
define('INCLUDE_CHECK',true);
require 'includes/connect.php';
require 'includes/functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('TheLoginSession');
// Starting the session
session_start();
if($_SESSION['id'] && !isset($_COOKIE['Remember']) && !$_SESSION['remembercheck'])
{
// If you are logged in, but you don't have the Remember cookie (browser restart)
// and you have not checked the remembercheck checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: index.php");
exit;
}
if($_SESSION['id'] && $_SESSION['new'] != 1){
header("Location: home.php");
exit;
}
?>
How can there be an update if nothing's changed?
Are you using a CMS or framework?
If it's all your own code, and you haven't changed anything, then nothing would have updated.
I've had an issue like this before but without more information, hard to know if it is the same issue. Mine had the symptom you describe (login with bad creds and get the authentication error, login with good creds and redirect back to login).
Mine was due to failing to include code to remove old session cookies. The login attempt 'works' but an old cookie also read and attempts to authenticate, fails (because it is too old), and kicks the user back to login.
If this is your issue, clear your site cookies and see if you can then log in.
If that works, you'll want to add some cleanup code to your logout and stale session handling. For instance, for logging out:
// per http://www.php.net/manual/en/function.session-destroy.php
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
session_destroy();
Again, just guessing at your issue here.

Logout system in php not working?

I have made a login and register system, which works flawlessly, and I am very proud of, but I cannot seem to get a logout function working.
My login system basically takes the database and scans it for rows that have both the username and password specified, and if it does, then it makes $_SESSION['loggedin']=1; and if it fails it makes it equal to 0.
Once the user is done, he/she clicks on a link that redirects to logout.php, and that is where the issues start. I have put session_start(); at the beginning of each page, but session_destroy, session_unset, and combinations of the two cannot seem to kill the session.
So I am wondering, is there a way that upon loading logout.php, it sets the $_SESSION['loggedin] to 0, and then redirects back to index.php(my homepage)? Which means it doesnt kill the session, but it would effectively log the user out. Any help is appreciated.
// Four steps to closing a session // (i.e. logging out)
// 1. Find the session
session_start();
// 2. Unset all the session variables
$_SESSION = array();
// 3. Destroy the session cookie
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
// 4. Destroy the session
session_destroy();
if session_destroy doesn't work, use instead:
unset($_SESSION['put your session in here']);
// logout.php
session_start();
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == 1) {
$_SESSION['loggedin'] = 0;
header('Location: index.php');
}
It redirects the user to to index.php, if $_SESSION['loggedin'] equals to 1, and sets $_SESSION['loggedin'] to 0.
I suggest you to have 3 files
1) login.php
session_start();
/*if user $_POST username and password is correct then*/
$_SESSION['loggedin'] = 1;
?>
2)logout.php
<?php
session_start();
unset($_SESSION['loggedin']);
$_SESSION['loggedin'] = 0;
?>
3)checkLogin.php
<?php
session_start();
if ( isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == 0 )
{
echo "<script type='text/javascript'>alert('You need to login !')</script>";
echo '<meta http-equiv="Refresh" content="0;URL=index.php" />';
flush();
exit();
}
?>
with 3 files if you want to control some page that require login before access you just include(checkLogin.php);
e.g. index.php is not require login then not include(checkLogin.php);
but memberProfile.php is require login before then include(checkLogin.php);

Categories