Why my code doesn't delete the $_SESSION variable? - php

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

Related

session_destroy() is not logging me out

Whenever I run the logout.php script then go back to a page that is protected without login it will have me still logged in
logout.php
<?php
session_start();
session_unset();
session_destroy();
header("Location: ../index.php");
exit();
?>
login.php
$userlogin = user_login($email, $password.$salt);
if ($userlogin==false){
$errors[]='Wrong email/password combination.';
} else {
//set the user session
$_SESSION['UserId']=$userlogin;
$_SESSION['LoginIP']=$_SERVER['REMOTE_ADDR'];
$db->query("UPDATE users SET ipadd='".$_SERVER['REMOTE_ADDR']."' WHERE user_id=".$_SESSION['UserId']."");
echo '<meta http-equiv="refresh" content="0; URL=index.php">';
Check logged in snippet
/* Check if user is logged in or not */
function loggedin(){
return (isset($_SESSION['UserId'])) ? true : false;
}
if (loggedin()==true){
$session_user_id = $_SESSION['UserId'];
$user_data = user_data($session_user_id,'full_name','username');
$rezult =$db->query("SELECT ipadd FROM users WHERE user_id=".$_SESSION['UserId']."");
while($rez = $rezult->fetch_assoc()){
if ($rez['ipadd']==$_SERVER['REMOTE_ADDR']) {
} else {
echo '<meta http-equiv="refresh" content="0; URL=logout2.php">';
}
}
}
Been look at posts with the same question but whatever I try still getting the same issue. Any advice would be extremely appreciated!
this is from php.net http://php.net/manual/en/function.session-destroy.php
Note: You do not have to call session_destroy() from usual code. Cleanup $_SESSION array rather than destroying session data.
so you just need $_SESSION = null, and logout should happen.
I think in your index.php file should have these line:
if(!isset($_SESSION["session_name"])){
header("Location: somewhere_mainpage.php");
}
It is better to make all pages have these line. These line will send header to another page if no session has started.
I believe that session_start(); function call should be on your login page when the user login data is correct, and in your logout PHP code, you should set
session_destroy(); or unset($_SESSION['UserId'];
Logout.php:
<?php
session_destroy();
/* * OR * */
//unset($_SESSION['UserId'];
header("Location: ../index.php");
exit();
?>
<?php
session_unset();
session_destroy();
header("Location: ../index.php");
?>
should work, otherwise you could unset the values
<?php
unset($_SESSION['UserId']); // Unsets the UserId Variable reuse for each variable
session_destroy();
header("Location: ../index.php");
?>
have you tried just session_destroy() ?
also I'm not sure wether you need session_start() when you are closing the session, from memory you only need it to start the session
I always like to destroy the server session, and client cookie, try to manually cover all options in case of any errors.
You can destroy the cookie in PHP with:
setcookie(session_name(), '', time() - 3600, $cookie_path, $cookie_domain, $cookie_secure, $cookie_httponly );
<?php
$cookie_path = "...";
$cookie_domain = "...";
$cookie_secure = "...";
$cookie_httponly = "...";
session_start();
session_unset();
session_destroy();
setcookie(session_name(), '', time() - 3600, $cookie_path, $cookie_domain,$cookie_secure, $cookie_httponly );
header("Location: ../index.php");
exit();
time() - 3600 makes the cookie expiry before the current time, which makes it invalid.
Another option to investigate is session_regenerate_id() on your logout pages. Some reference pages are below:
php.net - session-regenerate-id
https://stackoverflow.com/a/22965580/1246494

how to close the session and redirect to index page when browser in closed

I want to clear the session variables when the tab is closed but I could not find any solutions so far. here user without login they will enter the url dashboard.php means it will redirect to index.php, this condition is working fine, now user successfully login means it will go to dashboard.php page after that user close this tab and again they will enter dashboard.php page means i want to redirect the page in index.php, how can do this
<?php
session_start();
date_default_timezone_set('Asia/Kolkata');
include('dbconfig.php');
$email=$_POST['email'];
$password=$_POST['password'];
$password=md5($password);
$sql=mysql_query("SELECT id,username,email,password,is_user_type FROM login WHERE email='$email' AND password='$password'");
list($id,$username,$email,$pwd,$is_user_type)=mysql_fetch_row($sql);
if($pwd==$password){
$_SESSION['username']=$username;
$_SESSION['email']=$email;
$_SESSION['is_user_type']=$is_user_type;
$_SESSION['current'] = basename($_SERVER['PHP_SELF']);
header("Location:dashboard.php");
}
else{
echo "error";
}
?>
dashboard.php
<?php
session_start();
if(!isset($_SESSION['email']) && empty($_SESSION['email'])) {
header("Location:index.php");
}
if (isset($_SESSION['current'])) {
if (basename($_SERVER['PHP_SELF']) != $_SESSION['current']) {
session_destroy();
}
}
?>
First, your xyz.php file set a unique variable in the $_SESSION array which will act as a mark that the user has been on this page
$_SESSION['previous'] = basename($_SERVER['PHP_SELF']);
Then, add the following code on all pages, before any output to check if the user is coming from xyz.php
if (isset($_SESSION['previous'])) {
if (basename($_SERVER['PHP_SELF']) != $_SESSION['previous']) {
session_destroy();
unset($_SESSION['previous']);
}
}
To remove particular session data , try this
if($_SESSION[sessionvaribale] )
{
unset($_SESSION[sessionvaribale]);
}
To destroy all session data - try session_destroy()
Its already discussed by Stackoverflow
Refer Session destroy when logout

Destroying session for user login / NULL $_SESSION remnant

I'm trying to create a user login system for use on a website I'm building. I have the login script and register script, but I'm having trouble with the logout and destroying the sessions.
Here's my index code. It gets the database info in config (doesn't do anything with it yet), then runs check-login to make sure the user is actually logged in. It has a logout button that routes to logout.php
<?php
include_once("config.php");
include_once("check-login.php");
session_start();
$username = $_SESSION["username"];
?>
<html>
<body>
<h1>
Hello <? echo $username ?>! We're still building, but feel free to... wait?
</h1>
<form action="logout.php">
<input class="logoutbutton" type="submit" value="Logout" />
</form>
</body>
</html>
Here is my check-login.php file. Notice that anytime I link back to the index, I'm using a $_GET to post some information into the address bar. There is no place where I simply go back to index.php
<?php
ob_start();
include_once("../myreadingplanner_config/config.php");
if(($_SESSION['username']) != null){ //If user is already logged in...
$username=$_SESSION['username'];
header("Location: index.php?Message=AlreadyLoggedIn$username");
}
else {
if(isset($_POST['username']) && strlen($_POST['username'])!=0){ //if username is valid
$username = $_POST['username'];
} else {
header('Location: login.php');
}
if(isset($_POST['password']) && strlen($_POST['password'])!=0){
$password = $_POST['password'];
} else {
header('Location: login.php');
}
$SQLString = "SELECT TOP(1) * FROM Users WHERE Username = '$username' AND Password = '$password'";
$result = sqlsrv_query($conn, $SQLString) or die ("");
if($result != null)
{
$_SESSION['username'] = $username;
header("Location: index.php?Message=YouLoggedIn$username");
} else {
header("Location: index.php?Message=UserLoginNotFound&Username=$username");
}
}
ob_flush();
?>
And finally here is my logout.php, which should (in theory) destroy the session, and head back to index.php. When it gets back to index.php, index.php will reroute to login.php using the include_once("check-login.php");
<?php
session_start();
session_destroy();
header('Location: index.php');
?>
Just looking at my logic, there SHOULD be an infinite loop in the check-login, right? Because if the user is logged in, it should reroute to index, which includes check-login, which reroutes to index, which... etc.
If you want to check out the site for yourself, please go to www.myreadingplanner.com, and use this info to login (user will be deleted eventually)
Username: StackUser
Password: password1
So functionality wise, login.php should NEVER be visible unless you have a valid session, and when it does, it should say 'Welcome $username!'. But if you hit the logout button on index, it will still keep the session open, but it will be null.
Any advice on either why logout doesn't seem to fully logout the user OR why it is logging the user out but is keeping the NULL $_SESSION around?
To remove sessions use
unset($_SESSION['SESSION_VAR'] );
session_destroy(); //closes the session and prevents session riding
For more information I'd research session riding as you should close your session as soon as you can to prevent this.
Also do not unset the entire session global array.
//don't do this
unset($_SESSION);
First, have a look at index.php file. in that file, change the code below:
include_once("config.php");
include_once("check-login.php");
session_start(); // move the session_start function and place at the top of the script
$username = $_SESSION["username"];
change it, so that it becomes like this:
session_start();
include_once("config.php");
include_once("check-login.php");
$username = $_SESSION["username"];
This problem occurs because at the file check-login.php you do not declare the function session_start();
I have tested this problem. And it works!

Destroy all sessions but one

I have the same problem as this guy: Destroy session, but keep one variable set (solved)
I'm trying to destroy / unset all sessions except one session named 'id' when a user logout.
I don't want to unset each session manually because I have many sessions.
This is my logout.php
<?php
session_start();
foreach($_SESSION as $key=>$value) {
if($key !== "id") {
unset($_SESSION[$key]);
}
}
header("Location: login.php");
exit;
?>
This code currently unsets all sessions and does not keep the session named ID.
What am I missing?
You can reassign $_SESSION['id'] instead of deleting all of the others.
A little trick :)
<?php
session_start();
$tmp = $_SESSION['id'];
session_unset();
$_SESSION['id'] = $tmp;
header("Location: login.php");
exit;
?>
You can also do something like this:
$keep_alive = $_SESSION['id'];
Destroy all sessions:
session_start();
session_destroy();
Set session again:
session_start();
$_SESSION['id'] = $keep_alive;

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