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");
}
Related
I am getting issue in wordpress session where I am setting up the
session value on ajax request and the value is initialized as it
required but when I try to check this value after refreshing the
current tab. This value is reset. I observed two things in that:
If I try to fetch session value on the same page it is accessible
but in case of another page it is not accessible.
If the admin is logged in into wp then everything is working fine. I
am getting the value as I required.
I also used to try this code on another wordpress and it works fine.
Please let me know if there is any issue related to the permissions
or anything else.
Basically WordPress not make use of sessions, $_SESSION is one of the global variables which are unset by the WordPress. So, basically you have to declare session explicitly.
If you are using PHP 5.4>
if (session_status() == PHP_SESSION_ACTIVE) {
echo 'Session is active';
}
PHP_SESSION_DISABLED if sessions are disabled.
PHP_SESSION_NONE if sessions are enabled, but none exists.
PHP_SESSION_ACTIVE if sessions are enabled, and one exists.
Moreover, I will suggest to use as following (Paste this function in functions.php)::
function _mySessionSet()
{
if (session_status() == PHP_SESSION_ACTIVE) {
echo 'Session is active';
}
}
add_action('init', '_mySessionSet');
I am using same way to initialise session's in our WP website.
Hello Friends I am new at forum
I have create a simple login page name as index.php with following code:
// I have already starts session by session_start()
$qry="select empCode from relaxo_employee_info where empCode='".$username."' and empPassword='".$password."' and empPost='Executive'";
$result=mysql_query($qry);
if($row=mysql_fetch_array($result))
{
$_SESSION['UID']=$username;
echo $_SESSION['UID']; //prints session data successfully so think session set correctly.
?>
<script>self.location.href='executive/order_place.php';</script>
<?php
}
then at starting of order_place.php I continue the session by session_start() and the following code in it to check valid session
<?php
session_start();
if(isset($_SESSION['UID'])==NULL) // at this point $_SESSION['UID'] find automatically empty. somehow Its blank completely.
{
?>
<script>self.location.href='index.php';</script> //because of session finds empty it redirects to index.php
<?php
}
?>
and strange things are happens I just share with u which helps you understand my problem
1) the same code is run on localhost successfully and does not work on my domain
2) sometimes session works successfully but sometimes not with same code without any changes
So guys please solve my problem and help me to come out from this issue
if(isset($_SESSION['UID'])==NULL)
is kind of a weird approach if you want to compare the $_SESSION variable with NULL. Instead, try
if(is_null($_SESSION['UID']))
and see if the problem still occurs.
Try like this...
<?php
session_start();
if(isset($_SESSION['UID'])) // check whether session is set or not.
{
if($_SESSION['UID'] == NULL) // check session is NULL
{
header('location:index.php'); // redirect to index.php page
}
}
?>
if(isset($_SESSION['UID'])==NULL) is where your problem is. If true == null or false == null it's never going to work.
isset($_SESSION['UID']) tests to see if your variable is set.
in order for you to test it's value try something:
if( isset($_SESSION['UID']) && trim($_SESSION['UID'])!='' )
{
// execute code here
}
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)
I would like to know if anyone can help me with this $_SESSION variable problem. I want to add a script to a signup page that will allow someone that is already logged in to access the page from the backend and for someone who is not logged in to be redirected to the index page. Currently what is happening is that the page, when accessed from outside is redirected to index which is perfect, but from within the backend, when clicked on add user, it stays on the same page. Please excuse all the mistakes = still very new to PHP.
require 'function.php';
session_start();
if (isset($_SESSION['authenticated']) && !empty($_SESSION['authenticated'])) {
header('Location: ../../scripts/backend_login/signup.php');
} else {
header('Location: ../../scripts/backend_login/index.php');
}
You should start your session on every page where you use $_SESSION
session_start()
before the rest of your code
Start off by ensuring you have a session_start() on every page needing the session variable.
Next, change your code to this:
if (isset($_SESSION['authenticated']) {
if ($_SESSION['authenticated'] == true) {
header('Location: ../../backend_login/index.php');
} else {
header('Location: ../../backend_login/signup.php');
}
}
Try that and see
The true will only work if that is the value of the authenticated session
----EDIT----
The ($_SESSION['authenticated'] == true) is not vital, it is just another fail-safe to be double sure the correct session state is active, can be completed without this
I fixed my own problem. Here is the solution.
require_once('function.php');
session_start();
if (!is_user()) {
redirect('index.php');
}
thank you all for helping!
I have this written at the very first line on every page of my website.
include("restd.php");
and restd.php contains the following lines :
#session_start();
if(isset($_SESSION['id']))
{
}
else
{
header("location:index.php");
}
The problem i'm facing is that when ever i click or do something on my website. it logs me out and takes me to index.php.
im sure its something to do with the session. ive tried every single thing to avoid this problem but i ahve used restd.php because i dont want anyone to copy the url of someone and paste and get into the website.
anyone who is logged in only can view other's pages. if they arent logged in then they'll be redirected to index.php
EDIT : and guys a confusing thing is that all this is working fine on my testing server which is easyPHP-5.3.8.0 but this problem is coming up when i upload all the files to my server.
Your session directory (probably /tmp/) is not writable.
Check with session_save_path() if it is writable.
if (!is_writable(session_save_path())) {
echo 'Session path "'.session_save_path().'" is not writable for PHP!';
}
Do you actually set $_SESSION['id'] on a page...
What you are trying to do here is:
Start a session and load the $_SESSION from the session handler
Check if $_SESSION contains key 'id'
Redirect to index.php if $_SESSION['id'] is not set
Do you actually do this in index.php?
session_start();
$_SESSION['id'] = something;
you need declare $_SESSION['id'] :
file1.php
session_start();
$_SESSION['id'] = '123'
file2.php
include 'file1.php'
if(isset($_SESSION['id']))
{
}
else
{
header("location:index.php");
}
In my case I forgot that I had the PHP flag session.cookie_secure set to on, while the development environment was not TLS-secured.
More information about Session/Cookie parameters.
I know this is an old thread, but the following helped me with the same problem after hours of despair. Found on: http://php.net/manual/de/function.session-save-path.php
I made a folder next to the public html folder and placed these lines at the very first point in index.php
Location of session folder:
/domains/account/session
location of index.php
/domains/account/public_html/index.php
What I placed in index.php at line 0:
<?php
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();
?>
Hopefully this will save you time.
Check maybe your session path does not exist
so you can save PHP session path using:
ini_set(' session.save_path','SOME WRITABLE PATH');
Couple things:
your include file doesn't have the <?php ?> tags, so the content will not be evaluated as PHP
Session_start must be called before you start outputting anything. Is that the case?
You still don't even answer where you SET $_SESSION['id']. $pid = $_SESSION['id'] does not set the session variable. session_start() comes before ANYTHING session related, it's not shown before your include.
I had the same problem and found a work-around for it. If anybody can explain why the session is not read even when the cookie is there, please let me know.
<?php
// logged.php
// The PHP session system will figure out whether to use cookies or URLs to pass the SID
if(!isset($_COOKIE['PHPSESSID']) && !isset($_GET['PHPSESSID']) && authenticationRoutine(/* Returns true if succesfully authenticated */) ) {
session_id(uniqid("User--"));
session_start();
$_SESSION['id']=session_id();
}
?>
<?php
// Insecure restd.php (The user can forge a stolen SID cookie or URL GET request, but that is inherent with PHP sessions)
if(!isset($_COOKIE['PHPSESSID']) && !isset($_GET['PHPSESSID']) {header('Location: index.php')}
?>
.
[EDIT]
Even though the cookie was there and I prevented starting a new session, the session had not been read and started, so no session variables were available. In this case I check if the session has been started first (not using session_status() because it doesn't exist in PHP 3.5, which for some reason is the most widespread among hosts). If no session has been started within PHP, I check if it had been started before by testing the cookies and GET variables. If a session ID was found, the script resumes the session with that ID. If no ID is available, the user gets redirected to the index.
<?php
// restd.php
if(empty(session_id())) {
if(isset($_COOKIE['PHPSESSID']) && !empty($_COOKIE['PHPSESSID'])) {session_id($_COOKIE['PHPSESSID']);}
elseif(isset($_GET['PHPSESSID']) && !empty($_GET['PHPSESSID'])) {session_id($_GET['PHPSESSID']);}
else {header('Location: index.php'); exit(0);}
session_start();
}