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
}
}
Related
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();
}
?>
I have a file where the $_SESSION['username'] variable is first created:
<?php
$kullaniciadi = $_POST['kullaniciadi'];
$sifre = $_POST['sifre'];
if ((!$kullaniciadi =="") and (!$sifre =="")) {
include("db.php");
$sql = $sqlt->query("select * from uye where kullaniciadi='$kullaniciadi' and sifre='".md5($sifre)."'");
$kayitsayisi = mysqli_num_rows($sql);
if ($kayitsayisi == "0") {
header ("Location: login.php?hata=yes");
}
else {
$kontrol_ok = $sql -> fetch_assoc();
$k=$kontrol_ok["kullaniciadi"];
session_start();
$_SESSION['username']= $k;
header ("Location: homepage.php");
}
}
else {
header ("Location: login.php?hata=yes");
}
?>
It is called login_do.php (I send MySQL data from login.php form to here, and do the username and password check in this file).
Than in every other PHP file I have, I begin with:
<?php
session_start();
if (isset($_SESSION["username"])) {
echo 'loginok';
} else {
header ("Location: login.php");
}
?>
Than I have a logout.php, where the user is redirected to if he presses a button. logout.php file contains this:
<?php
session_start();
if(isset($_SESSION['username'])) {
unset($_SESSION['username']);
}
session_destroy();
header("Location: login.php")
?>
But it simply doesn't work. I mean if I go into my browsers cookies and delete the SESSION cookie by myself, than yes, the whole system works and I can't access any other php files than login.php unless I log in. But I need this to work with logout.php instead of me deleting the session from the browser by myself manually.
session_unset();
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.
--http://php.net/manual/en/function.session-destroy.php
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();
}
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);
I'm trying to make a login and logout script for a page but for some reason its not working very well for me. it seems to work fine until I try to logout. it seems to destroy the session variables, but it still lets me view the page.
heres my login code:
Code:
login.php
<?php
// Use session variable on this page. This function must put on the top of page.
session_start();
////// Logout Section. Delete all session variable.
session_destroy();
$Name=$_POST['Name'];
$Pass=$_POST['Pass'];
// To protect MySQL injection (more detail about MySQL injection)
$Name = stripslashes($Name);
$Pass = stripslashes($Pass);
$Name = mysql_real_escape_string($Name);
$Pass = mysql_real_escape_string($Pass);
$sql="SELECT * FROM reg1 WHERE uname='$Name' and pass='$Pass'";
$result=mysql_query($sql);
if(mysql_num_rows($result)!='0') // If match.
{
session_register("uname"); // Craete session username.
header("location:loged.php"); // Re-direct to loged.php
exit;
}else{ // If not match.
echo '<script type="text/javascript">
window.alert("Wrong UserName And Password");
window.location="index.php"
</script>';
}
// End Login authorize check.
?>
logout.php
<?php
// Inialize session
session_start();
// Delete certain session
unset($_SESSION['uname']);
// Delete all session variables
session_destroy();
// Jump to login page
header("Location: index.php?msg=Successfully Logged out");
}
?>
thanks to every one...
You are setting the session, but you are not checking it any where that whether it is set or not. means you are not checking that user is logged in or not.. you need to do like this
if (!isset($_SESSION['uname'])) /*If uname not set then it is a guest*/
{
//page contents for guest user
}
else
{
//page for authenticated user.
}
session_register() is deprecated as of PHP 5.3.0. Replace:
session_register("uname"); // Craete session username.
with:
$row = mysql_fetch_assoc($result);
$_SESSION['uname'] = $row['uname'];
Log out with (replacing session_destroy()):
////// Logout Section.
unset($_SESSION['uname']);
The final result will look like:
<?php
// Use session variable on this page. This function must put on the top of page.
session_start();
// Logout Section
if (isset($_SESSION['uname']))
unset($_SESSION['uname']);
// Login Section
$Name=$_POST['Name'];
$Pass=$_POST['Pass'];
// To protect MySQL injection (more detail about MySQL injection)
$Name = stripslashes($Name);
$Pass = stripslashes($Pass);
$Name = mysql_real_escape_string($Name);
$Pass = mysql_real_escape_string($Pass);
$sql="SELECT * FROM reg1 WHERE uname='$Name' and pass='$Pass'";
$result=mysql_query($sql);
if(mysql_num_rows($result)!='0') // If match. {
$row = mysql_fetch_assoc($result);
$_SESSION['uname'] = $row['uname'];
header("Location: loged.php"); // Re-direct to loged.php
exit;
} else { // If not match.
echo '<script type="text/javascript">
window.alert("Wrong UserName And Password");
window.location="index.php"
</script>';
}
?>
Logout script (syntax error fixed and session_destroy(); since unnecessary):
<?php
// Inialize session
session_start();
// Delete certain session
if (isset($_SESSION['uname'])) {
unset($_SESSION['uname']);
}
// Jump to login page
header("Location: index.php?msg=Successfully Logged out");
?>
How to check if logged in:
session_start();
if (isset($_SESSION['uname']))
{
// logged in
}
else
{
// not logged in
}
In your page that you want to be accessed only by logged in user, do you check the value of $_SESSION['uname'] ?
I think only session_destroy(); function is good enough to log you out. You need not to unset the 'uname'. And for those pages that will come after user logged in then you must apply some session check functionality at the top of each page...
if uname is the value you use to validate if the user is logged you should try to put first:
session_destroy(); and then the unset($_SESSION['uname'])
I hope this works for you....