Session destroy every time when page refresh - php

I am making admin panel there I implement login area when all information match to the database i mean login information username and password than i start session and redirect to index page but extremely confused why session null when i page refresh actually on index page i check that if session null than page redirect to login page.also using session_start(); on every page.i have been checked php.ini for lifetime there life time set 1440 default.
checking.php
session_start();
if((!empty($result)) && (!empty($result2))){
$_SESSION['admin'] = $user;
header("location:../../index.php");
}
else {
echo "Something wrong";
}
index.php
<?php
session_start();
if($_SESSION['admin'] == null)
{
header("location:system/access/login.php");
}
require('../config.php');
require('system/classes/userdata.php');
?>
Any one now the solution.

checking.php
//session should be started before every thing.
session_start();
if((!empty($result)) && (!empty($result2))){
$_SESSION['admin'] = $user;
header("location:../../index.php");
}
else {
echo "Something wrong";
}

maybe its because of the null thing, try this
if(isset($_SESSION['admin']){
//write your code
}
Reason being that a NULL is not equal to a NULL

#Mubo, session should not be started before everything, especially if you store objects in session.
#user3163274, this can be problem with sessions configuration, it can be badly configured cookies, or perhaps you got session cookies disabled at all (by default cookies are enabled). Problem can be caused by data you hold in session (especially if you hold there objects).
But if i can suggest, stop using relative paths for includes/requires and redirections. Also, if you want to test data against nulls use equality operator like === (it also checks the type)

Related

Not able to determine when session is active in PHP

So I want to be able to tell, in PHP, whether a session is currently active. I thought that this would be easy by either using session_status() or session_id(), but both return inconclusive results.
My PHP looks like this
if (session_id() == "") {
echo json_encode("nope");
} else {
echo json_encode("yep");
}
if (session_status() === PHP_SESSION_DISABLED) {
echo json_encode("disabled");
} elseif (session_status() === PHP_SESSION_NONE) {
echo json_encode("none");
} else {
echo json_encode("active");
}
$handler = new DatabaseSessionHandler();
session_set_save_handler($handler, true);
session_start();
And I have an Angular app making http calls to this script to basically activate its session.
I've been testing this, and when I visit the site for the first time, no session_id is found and the session_status() returns back "none", as they both should. But the problem is, when I refresh the page, and this PHP script is runs, but this time I have an active session (the PHP session cookie shows up in my browser), session_id is still acting like none exists. And also, session_status() returns back, mistakenly "none".
Any ideas would be greatly appreciated, thanks!
Edit 1: A few people have mentioned that putting the session_start() in front of testing if it is active or not should work. When I do this, a session_id is always found, and the session_status() always returns back "active". Even when a fresh new user visits the site, this still happens.
The session won't be active until you call session_start(), which you don't do until after testing to see if the session is active.
You should call session_start() at Top of the page and then perform the condition on it. In your case you are not starting session and you are testing for it.
I am not sure if this will solve your problem, but you could check if your session directory is writable:
if (!is_writable(session_save_path())) {
echo 'Session path "'.session_save_path().'" is not writable for PHP!';
}
A question related to that is at PHP Session not Saving.
Elsewhere try the following:
if (session_id() == "") {
session_start();
echo json_encode("nope");
} else {
echo json_encode("yep");
}

is there a delay in setting session variables? failing on first attempt only

I have a page, login.php, that processes a username and password and if successful it sets session variables and then redirects the user to home.php. The relevant part of login.php is here:
if ($pwdHash == $storedpass) {
$success = true;
$sessionStatus = session_status();
if ($sessionStatus !== PHP_SESSION_ACTIVE) {
session_start();
}
$_SESSION['user_id'] = $user;
$_SESSION['logged_in'] = true;
session_write_close();
header('Location: http://www.examplesite.com/home.php');
header("HTTP/1.1 303 See Other");
die("redirecting");
}
Then home.php tries to collect the session variable
$sessionStatus = session_status();
if ($sessionStatus !== PHP_SESSION_ACTIVE) {
session_start();
}
$loggedIn = $_SESSION['logged_in'];
The problem is that on the first login attempt, $_SESSION['logged_in'] is undefined and generates an error, even though login.php was successful.
Notice: Undefined index: logged_in
A var_dump of $_SESSION returns an empty array, but sessionStatus reports that the session was already started, it did not have to execute session_start.
This forces the user to log in a second time, then everything is fine. So is the redirect just happening too fast for the session variable to get set? Should I put a delay in the redirect? (and how would I do that?) Or is this something else that I'm doing wrong?
EDIT: I've checked with my host based on an answer to a similar question and confirmed that a session would never be served by more than one server and there is no need to enable sticky sessions or anything like that. I've also updated the code above based an answer offered below and some other research but the error persists.
The session is probably automatically saved when the script ends. You redirect before the script ends.
How long your script takes to really end depends very much on what other code needs to wind down. It is better to explicitly save the session.
How to do this depends on what kind of sessions you use. One type can be closed like this:
http://php.net/manual/en/function.session-write-close.php
If that's the one you're using do this:
if ($pwdHash == $storedpass) {
$success = true;
$_SESSION['user_id'] = $user;
$_SESSION['logged_in'] = true;
session_write_close();
header('Location: http://www.examplesite.com/home.php');
header("HTTP/1.1 303 See Other");
die("redirecting");
}
And the session should be available to the next page when you redirect.
If your sessions work differently, you have to adapt the code, of course. The point I'm trying to make is: Never put a delay in your code. It's unreliable, and pointless. Simply save the session before you redirect.
I have experienced the same issue while writing the session content to the database.
To make it work I have added the sleep() function before setting the session variable, just like below.
sleep(2);
$_SESSION['GUID'] = uniqid(time().rand());
It resolves the issue for me.
We have observed this issue when the page hits are frequent but if one or two users are accessing the page it works as expected.
I have encountered this same issue with a login page but none of the suggestions work for me. The only thing I've found that does work is redirecting the page to itself after 1 second and then checking the session variables to see if the login was successful...
startSession(); // assigns all the login session variables, etc.
header('Refresh: 1; URL=/[THIS_PAGE].php'); // [THIS_PAGE] = the current login page
However, this is a very inelegant solution and I don't like using it. But it "works".
This problem persists. In my case, the user login goes without a problem to the protected homepage, but clicking on a menu link causes the user to be dumped back to the login page to login again. A check on certain Session values (required for both pages) shows these are not set on going to the specific menu link (while other menu links cause no problem). The code requiring a session value is the same in all cases. Not all users experience the problem. Seems that those with less robust connections to the internet always experience this problem. Others, never.

PHP How to display page based on session?

I am making a website. Most of it is available to anybody visiting the site, but a small portion of it requires you to register to view. I have set up the login with Sessions. After someone logs in, it sets this:
$_SESSION['login'] = TRUE;
In one of the exclusive pages, at the top of the code before the content, I have written
if ($_SESSION['login'] == FALSE) {
header("loginpage.php");
}
However, if somebody is not logged in, that variable does not exist, and I end up with an error. Is there any other way to check if somebody is logged in? I would like something similar to what I already have, because I don't want to have to change everything.
You can use isset function to determine if a variable is set and is not null.
if (!isset($_SESSION['login']) || $_SESSION['login'] == FALSE) {
//user isn't logged in
header("loginpage.php");
}else{
//user is logged
}
Check the manual.
if(!#$_SESSION['login'])
{
header("location: logingpage.php");
exit();
}
Simple solution : in the first page (or first script) of your website, create the session variable with value "false" :
<?php
session_start();
$_SESSION['login'] = FALSE;
?>
And, after some successfully logins you change the value to TRUE (as you are already doing) :
$_SESSION['login'] = TRUE;
This way the session variable will always exist, and you will not have problems with "unset" variables.
Do you have a script that always runs before each page executes? If not, this is a great place to set up any utility functions or initialize variables, like $_SESSION['login']. You can set a default false value for $_SESSION['login'] there. Then you have a reliable default value, which is a good practice for a variable that's important, like this one.
You could use this to check if it's set and assign a default:
//Right after starting the session
if (!isset($_SESSION['login'])) {
$_SESSION['login'] = false;
}
If it's already got a value, this will be skipped.
You can also add an # before a variable when you want to use it but you can't be sure it exists. This will suppress warnings about the existence of the variable, but I think it's better to know what the default value should be. Sometimes it's useful to get those warnings.

PHP detect if session cookies are disabled

I know that with sessions in php, a cookie that stores the session ID is set on the client's side. The client can turn off these cookies, which I presumes makes sessions not work. How can I detect if the client has disabled the session cookies?
You can use javascript navigator.cookieEnabled. This returns true or false.
So
if(navigator.cookieEnabled)
//do something
else
//do something else
assuming you started a session on a previous page...
<?php
if(session_status() == PHP_SESSION_ACTIVE)
{
echo 'cookies & sessions enabled';
}
else
{
echo 'no cookies or sessions';
}
?>
or you're looking for a non-session cookies as well.
<?php
if(!empty($_COOKIE))
{
echo 'cookies are tasty';
}
else
{
echo 'no cookies to eat';
}
?>
with a pure php solution you can't check if sessions/cookies are enabled without setting a cookie on a previous page
If you know you MUST use a session, the usual approach is to redirect the user instantly at the start while trying to set a cookie, and then complain about the cookie not being set on the second page.
User goes to http://www.example.com
System sets a cookie (maybe only starts the session, maybe a dedicated test cookie).
System redirects to http://www.example.com/?cookietest=true
On that page, if the cookie is not sent back, complain to the user.
On the other hand, most of the time a session really is not needed if you do not have to log someone in. And IF you do, most users will understand they need to allow cookies, because otherwise the login will fail.

session protection

I am creating a webpage bit by bit, testing parts of the webpage ideas. I want to learn how to session protect a page. I have already password protected a page seccsesfully, but anybody can access the page by typing in the url. i want to session protect my page so no one can do that. i have three pages: index.html, which has the form which sends the the password.php, the password.php, which makes sure that the password and username are correct using "if statments"(here is the "if statment")
if ($username == 'mgmb99'){
if ($password == 'mgmb91mas'){
header('Location: youhere.php');
} else {
echo 'your username or password is wrong. go back to login page ';
}} else {
echo 'your username or password is wrong. go back to login page ';
};
, and the youhere.php which is the page once you logged in.
$_SESSION['connect']=0;
Sets the connect value in session to be 0.
Currently this check:
if((!$_SESSION['connect']))
Will always return true because if $_SESSION['connect'] is unset then !$_SESSION['connect'] will be true. Likewise if(!0) will be true.
Try setting $_SESSION['connect'] to true or 1 or the like or, alternatively, change the check to be:
if(!array_key_exists('connect',$_SESSION))
( ! $_SESSION['connect'] ) will is true when the session variable isn't set but also when it is set to 0. So if you want to protect youhere.php, you need to assign another value and check for it.
Also session_destroy() will delete all session variables, so you login, you go to youhere.php but if you refresh the site, you will instantly be logged out
There is a plethora of information on Sessions on the PHP website.
http://www.php.net/manual/en/intro.session.php
Here's an example with storing and killing session variables.
http://www.php.net/manual/en/session.examples.basic.php
To set a Session var:
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
?>
To kill the session var:
<?php
session_start();
unset($_SESSION['count']);
?>

Categories