Session doesn't get cleared - php

I have a google chrome extension talking to a PHP script via XHR. I have a flag in the PHP script to check if a button is clicked in a popup if proper POST data is sent. If this button is clicked, the current session needs to be destroyed and when new data is entered by clicking the add button it shouldn't be appending data to an existing session but start a new one instead. It's currently just re-appending the data to the array. It's as if the clear session command is being ignored, however the IF statement is being called correctly to the console. How do I get the clear session statement to clear the session?
PHP script:
<?php $json = $_POST['data'];
if($json['button'] == "clear"){
session_unset();
session_destroy();
echo 'session destroyed!'; //being called to console
exit();
}
if (!isset ($_COOKIE[ini_get($_SESSION['data'])])) {
session_start();
}
if(!isset($_SESSION['data'])){
$_SESSION['data'] = $json;
} elseif (isset($_SESSION['data'])){
array_push($_SESSION['data'], $json);
}
print_r($_SESSION['data']);
?>

You must call session_start() first:
if($json['button'] == "clear")
{
session_start(); // <-- first
session_unset();
session_destroy();
echo 'session destroyed!'; //being called to console
exit();
}

Related

PHP How to completely destroy a session after leave the page

I want to make a simple PHP page where you can only access if you log in first. My code is something like this:
if (the user logged in correctly) {
session_start();
echo "THE HTML PAGE. (I did this in echo because I only want to show it for the logged in users.)";
} else {
header ("Location: index.html");
die();
session_destroy();
}
So my goal is that, when the user click onto the "Go back on page" button, the session gets destroyed, and only start a new after logged in. But now, if the user click onto the "Go back on page" button, than click onto the "Go forward on page" button. it says, Document Exired. It's cool, but if I refresh the page, I can access the page without login.
Here is a solution
// put on top of every page
session_start();
function is_logged_in(): bool
{
if (isset($_SESSION['email']) && isset($_SESSION['id']) && isset($_SESSION['is_logged_in'])) {
return true;
} else {
return false;
}
}
function is_auth()
{
if (!is_logged_in()) {
session_destroy(); // change happend here
header("Location: index.html");
die();
}
}
is_auth();
// add your code here
if(isset($_SESSION['email']) && isset($_SESSION['id']))
{
return true;
}
else
{
return false;
}
// and then call this function in header file to check.
header ("Location: index.html");
die();
session_destroy();
Regarding session destruction, you cannot do it that way. See below:
First you need to destroy the session.
Then you need to redirect the user.
Correct:
session_destroy();
header ("Location: index.html");
die();
sometimes unset function also works see unset and destroy are two seprate function,
unset is useful for unsetting the some values like email,id,name etc and destroy completely destroys session, so make sure destroying the session you again not need the session so try to use unset().

PHP login script in a separated file

I have been developing the following php script (+ sqlite database) to create a login for my web.
Up to now I had used just one PHP file, but now I want to use different files for login and protected contents, I mean, I used to have all my web in one file php (contents and password script were together) but now I want to detach it in different php files (one for the login, login.php, and other phps protected: index.php, calendar.php...)
I used this code to password-protect php content:
<?php require_once "Login.php"; ?>
but it doesn't seem to work: it displays the form to login next to the content I wanted to protect.
This is the php script I'm using as login.php:
<?php
$db = new PDO('sqlite:data.db');
session_start();
if (isset($_GET['logout'])) {
unset($_SESSION['pass']);
header('location: index.php');
exit();
}
if (isset($_SESSION['timeout'])) {
if ($_SESSION['timeout'] + 4 < time()) {
session_destroy();
}
}
if (!empty($_POST['pass'])) {
$result = $db->query("SELECT user,password FROM users");
foreach ($result as $row) {
if (password_verify($_POST['pass'], $row['password'])) {
echo "Welcome! You're logged in " . $row['user'] . "! <a href='index.php?logout=true'>logout</a>";
$_SESSION['pass'] = $_POST['pass'];
$_SESSION['timeout'] = time();
}
}
}
if (empty($_SESSION['pass'])) {
echo '<form method="POST" action=""><input type="password" name="pass"><form>';
}
?>
MY QUESTION IS: How can I use my php script to protect different files?Is there any way to embed a logout link too?
One way is to store a token in session variables when a user logs in. Confirm the token is there on each page, if it isn't redirect the user to the login page. For example assert_login.php:
<?php
session_start();
if('' == $_SESSION['token']) {
header("Location: login.php");
exit();
}
?>
Then, in the PHP at the top of each of your pages:
<?php
require('assert_login.php');
?>
You can also clear the session variable on logout, logout.php for example:
<?php
require('assert_login.php'); // has session_start() already
$_SESSION['token'] = ''; // empty the token
unset($_SESSION['token']); // belt and suspenders
header("Location: login.php");
exit();
?>
I was also going through same issue & the way I solved it:
PSEUDO CODE:
PHP SESSION START
if(isset(GET(logout){
SetLogout();
die()}
$redirect=false
if not session[auth] exists
if SERVER REQUEST METHOD IS POST
$redirect=true;
if POST(username) && POST(pass) exists
Sanitize both of them & assign to $user& $pass
if user == "John" && $pass == "secret"
Go To SetLogin();
else{
Go To SetLogout();
echo "Wrong Username or Password"
drawlogin();
die();}
} //user pass comparing ends
} //Server method is NOT POST, so maybe it is GET.
//Do nothing, let the control pass to next lines.
}//SESSION(auth) does not exists, so ask user to login
else {
drawlogin();
}
//Post-Redirect-Get
if ($redirect)
redirect header to this same page, with 301
die()
// Secret Content here.
function SetLogin($user){
$SESSION(auth) = TRUE;}
function SetLogout($user){
if SESSION(auth) exists
unset($SESSION(auth))
redirect back with 301, without query string //shake ?logout
}
function drawlogin(){
echo all the HTML for Login Form
What it does is, it checks various things/variables, and if all passes, the control passes to Secret Content.
Save it as pw.php, & include it on top of any file you want to protect. Logout can be triggered by Logout
Note that this is just a pseudo code, typed on a tablet. I will try to update it with actual version. It is not checked for errors. Use all standard PHP Security precautions..

PHP session is dying on refresh why?

Hi each time im refreshing or click a button that reload my index page ... which is my main page, the session dies .... here is a simple of code :
//session.class.php
<?php
session_start();
$_SESSION["EMAIL"] = "";
$_SESSION["LOGED"] = 0;
?>
//index.php
<?php
include_once ('session.class.php');
if (isset($_GET['login'])) {/// it a button submit in my form that use for login
$_SESSION["LOGED"] = 1;
include ("/module/Users/profile.php");// class that show profile if login an
// password is good
echo "session = ".$_SESSION["LOGED"];
}
if ($_SESSION["LOGED"] == 0) {
echo userFormLogin();//show login
echo "<a href=index.php?content=register>Register</a>";
}
?>
TY every one :D
Every time you load page, your EMAIL and LOGED session variables get reset. You don't need to declare them, SESSIONS don't exist until you make one. You are basically creating session but when you load page it gets set to 0 and you ask for login again.
You should use:
if(isset($_SESSION['LOGED'])){
actions for logged in
}
else{
show login page
}

php session lost after submitting form

The code below page keeps session on GET requests or refreshing browser, but when I submit a form the session data is lost.
$user=$_POST['user']; $pass=$_POST['pass'];
if ($_POST['user'])
{ if($user==$un and $pass=$pw)
{ $_SESSION['uid']=$Xid;header('Location: '.$uri.'?welcome'); }
else { $msg="chybny login"; }
}
if(isset($_GET['logout'])) { session_destroy(); header('Location: '.$uri); }
$cnt=$_SESSION['cnt']+1; $_SESSION['cnt']=$cnt;
Above is the code for login which re-directs me to the welcome page as it was verified, however the session is lost. If I just refresh or repeatedly load the page without submitting, the session holds by echoing the session variable cnt (counts up 1,2,3,...)
After submitting the form, I see session is lost and too cnt variable is reset?
I usually don't work with session directly try the following, place it a the top of your script :
session_start();
$uid = $_SESSION['uid'];
$cnt = $_SESSION['cnt'];
then work with the variable instead
The problem is likely your 'and' statement. It should be &&. The condition is not going to be true.
If you're 100% sure the code is all fine and the PHP.ini is the problem, based on your comments above. Look at this link at check the settings in the .ini http://php.net/manual/en/session.configuration.php
To pass the current session to the next page... I believe is what you are asking...
You are currently not passing the session to the next page and use session_start() at the top of the next page.
Change line 4 to:
{ $_SESSION['uid']=$Xid;header('Location: '.$uri.'?'.SID.'&page=welcome'); } // Where "page" is the name of the data you are retrieving
Or, you can save the session data to a cookie and then retrieve it on the next page.
You can alternately name the session when you use session_start("NameHere") on each page, however if the visitor has recently visited and the session not destroyed, they may see parse errors, if you have them enabled.
First of all, make sure that the the first thing you do on every page is to start a session (I recommend calling it once in a header file that you require on all of your sub sites).
So that you have session_start(); everywhere in the system.
Second of all, tighten up your code; make it easier to read. Something like
$userName = isset($_POST['userName']) ? $_POST['userName'] : false;
$password = isset($_POST['password']) ? $_POST['password'] : false;
$logout = isset($_POST['logout']) ? $_POST['logout'] : false;
$url = '../index.php';
if(!($logout))
{
if($userName && $password)
{
if($userName == $un && $password == $pw)
{
$_SESSION['loggedIn']=true;
$_SESSION['uid']=$Xid;
$_SESSION['message']="success";
}
else
{
$_SESSION['loggedIn']=false;
$_SESSION['message']="fail, incorrect login information.";
}
}
else
{
$_SESSION['loggedIn']=false;
$_SESSION['message']="fail ; username and password not submitted.";
}
header("Location: $url");
}
else
{
session_start();
session_destroy();
session_start();
header("Location: $url");
}
And if you want to display unqiue content depending on whether a user is logged in or not, then you can simply check if the login session is set or not, on each page, instead of modifying the header for that.

Start session after destroy php

I have a logout file for my web application. I would like to create a session after the logout so that I can echo a logout success message. My logout code works but I am unable to create a new session after destroying the previous one.
What is the best way to do this, see code:
//LOGOUT.PHP
session_start();
//// unset all $_SESSION variables
session_regenerate_id();
session_unset();
session_destroy();
$_SESSION['logoutsuccess'] = 'You have successfully logged out.';
header("Location: /login/");
exit;
//LOGIN.PHP (ECHO SUCCESS MESSAGE)
if(isset($_SESSION['logoutsuccess']))
{
echo '<div class="success">'.$_SESSION['logoutsuccess'].'</div>';
unset($_SESSION['logoutsuccess']);
}
I would like to avoid passing variables in the url if possible.
Call session_start() again after session_destroy()?
Just start a new session:
session_start();
session_destroy();
session_start();
$_SESSION['food'] = 'pizza';
Instead of trying to store it as a session variable, you could check the referer and check for /logout/
if(strpos($_SERVER['HTTP_REFERER'], 'logout') !== false) {
echo 'You have successfully logged out.';
}
session_id($session_id_to_destroy);
session_start();
session_destroy();
session_commit();

Categories