session is always empty outside of the file where is generated - php

Why I am getting an empty array of the session when I am trying a var_dump in another page?
In the server, the session is stored without any content, only with the name of the id.
With cookies all works well. Sometimes (yes, sometimes), I restart the server, and then, the sessions works well too. What may cause this issue?
Maybe a bug of the php 5.1.6? or a problem in the config of the server?
index_2.php
<?php
session_start();
$_SESSION['xxx'] = "tessstsse";
var_dump($_SESSION);//here show the correct session
header( 'Location: index_3.php');
index_3.php
<?php
session_start();
var_dump($_SESSION);
The output of this will be:
array
empty

Give this a try.. if this works I'd re examine your code else it is probably an issue with your server...
page1.php
<?php
session_start();
$_SESSION['auth'] = "true";
$_SESSION['superhero'] = "batman";
?>
Click here
page2.php
<?php
session_start(); // start the session before using it
//echo $_SESSION['auth']; // will output 'true'
print_r($_SESSION);
?>
destroy.php
<?php
session_start(); // start the session before using it
session_destroy(); // deletes the current session..
?>

I have the web server without space to store the session content.
0% of free space. Delete some data and the problem is solved.

Related

PHP Sessions Variables & Authentication

I have two pages which I need to pass session information between them. Here's page one.
<?php
session_start();
echo session_id()."<br>";
echo $_SESSION['test']."<br>";
Page two.
<?php
session_start();
echo session_id()."<br>";
$_SESSION['test'] = 'test';
echo $_SESSION['test'];
Page two is in a different directory (same domain), and has Windows Authentication on. Page one is using anonymous authentication. From the output I can see the session ID is the same, but page one doesn't echo the test variable set from page two.
I'm running PHP in IIS 8.5 on Server 2012 R2.
Any help is appreciated.
To clarify, I am calling page two first, and page one will not show the variable.
You need to initialize the variable with a value first before using it.
First run page2.php so, that value of $_SESSION['test'] is set to test
using $_SESSION['test'] = 'test';
Now, run page1.php there you can see the value of $_SESSION['test']
using echo $_SESSION['test']."<br>";
you can also follow these steps to make use of session in a simple way so that you don't have to do session_start() again and again
1. config.php having session_start();
2. page1 having include_once('config.php');
echo session_id()."<br>";
echo $_SESSION['test']."<br>";
3. page2.php having include_once('config.php');
echo session_id()."<br>";
$_SESSION['test'] = 'test';
echo $_SESSION['test'];
Try closing your session in the first page, it's possible that your session file is still open when the second page is called, so you're not seeing the data. Try adding session_write_close() to the first page called.
http://php.net/manual/en/function.session-write-close.php
The issue was with permissions on the session save path. I changed the path to where both directories could write and it works.

Session data not saved on disk and also when processing another page

I am trying to process simple HTML form when on submit page1.php is called. page1.php internally calls page2.php
page1.php looks like this:
<?php
session_start();
$sesid = session_id();
$_SESSION['cname'] = #trim(stripslashes($_POST['companyname']));
$_SESSION['fname'] = #trim(stripslashes($_POST['firstname']));
$_SESSION['lname'] = #trim(stripslashes($_POST['lastname']));
$_SESSION['eaddr'] = #trim(stripslashes($_POST['eaddress']));
echo " $_SESSION[cname]" ;
echo " $_SESSION[otprdsvc]";
include_once $_SERVER['DOCUMENT_ROOT'] .'/appconnector.php';
?>
Page2.php looks like this:
<?php
echo "$_SESSION[cname]";
?>
I do get output of echo $_SESSION[cname]; on first page. However, data is not saved to disk when I check session cookie.
Here is data from session cookie on disk:
cname|s:0:"";fname|s:0:"";lname|s:0:"";eaddr|s:0:"";webaddr|N;cmsg|s:0:"";drpopt|N;otprdsvc|s:0:"";securimage_code_disp|a:1:{s:7:"default";s:6:"n55Zmr";}securimage_code_value|a:1:{s:7:"default";s:6:"n55zmr";}securimage_code_ctime|a:1:{s:7:"default";i:1398221627;}
I don't understand why cname is coming as "" ( no data / null ) where in fact I am getting response.
Little bit of history what I have done till now
session.save_path was not enabled earlier in php.ini file so I enabled it.
I was using autocomplete = off in html form earlier so I removed it.
securimage is packaged solution I am using for captcha which is saving cookie data but I don't know+understand anything what it did internally.
Can you please suggest what needs to be done in order to have session cookie data:
saved & available on disk in file
make it available when page2 is processed.
Thank you in advance and I apprecriate your time and comments.
You will have to always do session_start(); on every page before using the $_SESSION variable.
So page2 will be
<?php
session_start();
echo "$_SESSION[cname]" ;
?>
Try using this:
For page1.php
....
echo $_SESSION['cname'];
echo $_SESSION['otprdsvc'];
....
For page2.php
<?php
session_start();
echo $_SESSION['cname'];
?>
You have to use session_start() on every page wherever you want to call the session data.
I have solved this problem. Page2.php was submitting itself so session data was getting lost. I now have modified flow of data processing. I also used session.write_close() after writing data to session variables on page1.php so that also helped.
Thank you for your comments.

PHP Session not Saving

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();
}

Sessions not working PHP

My website doesn't start a session when I visit, I don't know why but my website works like this:
<?php
session_start();
$title = "Home";
include("include/header.php");
include("include/functions.php");
?>
...HTML stuff here...
<?php
include("footer.php");
?>
But when I check with Cookies (add-on for Firefox) there are no sessions started... I used session_regenerate_id(); but it doesn't work at all.
It fails to log in since there are no sessions, I do not have any session_destroy() in my website, only in the logout.
But funny thing is, when I login (without refreshing or navigating just yet) and then click on the logout button, there is a session on my website, then when I log in again, it tells me that I am logged in BUT if I login and navigate or refresh, it doesn't tell me that I'm logged in since there are no sessions...
Logout:
<?php
session_start();
session_destroy();
setcookie("cookie-name", "", time()-60, "", "", 0);
header("Location: ../index.php");
exit;
?>
What do I do?
You must have session_start() at the beginning of every file that is being accessed and uses sessions. The name is misleading, session_start() actually doesn't start a new session but initialzes PHP session menagment.
Not sure if it's related, but there was a strange PHP quirk that required the SESSION_START() to be on the line immediately below the <?php tag. Something about whitespace and extra things above the session used to make it go haywire for me. I've been using Zend of late, which avoids that issue with its own session handling system.
You might try doing a print_r($_SESSION) to see if there's anything in the session array at all.
It's probably because you are not setting a session in either of the examples you have given, you have to have a line like the one below to actually create a session, and then to access the session variables on all subsequent pages you need session_start();
$_SESSION['example'] = 'something';
It doesn't look like your setting anything in the session or the cookie.
If you want to pass information around in the session you'll need to assign the necessary values in the $_SESSION variable.
For example on your main page you can do:
<?php
session_start();
$_SESSION['myVariable'] = "my text";
?>
And then on any subsequent pages you can access the variable you've set.
<?php
session_start();
echo $_SESSION['myVariable']; //This will print "my text"
?>

PHP SESSION data lost between page loads with WAMPserver 2.0 on localhost

I have a PHP authentication system on my website using the $_SESSION variable.
A form submits a username and password to the file "login.php". It is handled like this:
<?php include '../includes/sessionstart.inc.php'; ?>
<?php ob_start(); ?>
if($_POST){
$q = mysql_query("SELECT id, company FROM users WHERE username = '".mysql_real_escape_string($_POST['username'])."' AND password = '".md5($_POST['password'])."'");
if(mysql_num_rows($q) >= 1){
$f = mysql_fetch_Array($q);
$_SESSION['company'] = $f['company'];
$_SESSION['id'] = $f['id'];
$_SESSION['logedin'] = true;
session_write_close();
ob_clean();
header("Location: index.php");
}
Afterwards, index.php is loaded and checks whether 'logedin' is true.
<?php include '../includes/sessionstart.inc.php'; ?>
<?php if(!isset($_SESSION['logedin'])) header('Location: login.php'); ?>
On my production server, it continues, but on my Wampserver, it reverts back to login.php. I notice that Wampserver is very slow in page loading, this might have to do something with it. That's why I included the session_write_close, to make sure session data is saved before the pages are switched, but it doesn't help.
The contents of session_start.inc.php are simply:
<?php
session_start();
?>
I used to have more code in there, but at the moment it's just this. The problem also existed before I started using an include file.
Does anybody have an idea what I'm doing wrong? Why doesn't Wampserver transmit my SESSION data to the next PHP file?
WAMP server 2 - settings are not set by default for $_SESSION var.
PHP.ini
requires the following settings
C:\wamp\bin\apache\apache2.4.2\bin\php.ini
session.cookie_domain =
session.use_cookies = 1
session.save_path = "c:\wamp\tmp" ;ensure the \ is used not /
Session testing -
load.php -- load $_SESSION var.
<?PHP
session_start();
$_SESSION['SESS_MEMBER_ID'] = 'stored variable';
session_write_close();
header("location:print.php");
?>
print.php -- print $_SESSION var.
<?PHP
session_start();
var_dump($_SESSION);
?>
run the script in your browser var_dump() should produce results
go to c:\wamp\tmp Files containing the session data will appear here.
First of all: the index logedin seems strange for keeping track of a user being logged in. Is this just a typo on SO, or really a code-typo?
Second (depending on the desired behavior), try another approach for making pages login-protected. Your page should look something like
<?php
include 'login.inc.php';
if(authorized()) {
// put some more script here, if needed
?>
// put some plain HTML here
<?php
}
?>
Where login.inc.php handles the session, cookies. In particular, the authorized function should return TRUE if a client is already logged in. If a client is not logged in, it should display a form with action $_SERVER['PHP_SELF'] and return FALSE. If you name the submit-input something like login_submit, you can let login.inc.php handle the verification.
This way, you don't need to refer users to a dedicated login page, and after logging in, user are directly shown the requested page. You can tweak this a bit to make query-strings persistent through login as well.
Try to replace
if($_POST){...}
with
if( isset($_POST['username']) && isset($_POST['password']) ){...}
... at least for debugging purposes. It's possible that some different settings are causing a non-empty $_POST array where it's not expected.
Also, your code seems to be missing exit() calls after header() redirections. Sending an HTTP Location header doesn't automatically stop your script.
I had this problem using WAMPSERVER for development on /localhost. I needed to change session.use_only_cookies either in-line or in the php.ini setting from
session.use_only_cookies = 1
to
session.use_only_cookies = 0
Explanation
Using default cookie-based sessions was working as expected but I needed a cookie-less solution. A test starting page:
<?php
// page1.php
ini_set('session.use_cookies', '0');
session_start();
$_SESSION['time'] = time();
echo '<br />page 2';
?>
The session data was created and stored successfully in the WAMPSERVER temp directory, e.g., C:\wamp\tmp\sess_0rkdlonl5uia717rf03d4svs16. The link generated by the above code looks similar to (note the UID matches the session data file name):
page2.php?PHPSESSID=0rkdlonl5uia717rf03d4svs16
But the destination page2.php was throwing undefined errors for the variable 'time' whilst attempting to retrieve the session data:
<?php
// page2.php
ini_set('session.use_cookies', '0');
session_start();
echo date('Y m d H:i:s', $_SESSION['time']);
echo '<br />page 1';
?>
By setting session.use_only_cookies FALSE in either the script before session_start();:
ini_set('session.use_only_cookies', '0');
or changing it globally in php.ini:
; This option forces PHP to fetch and use a cookie for storing and maintaining
; the session id. We encourage this operation as it's very helpful in combatting
; session hijacking when not specifying and managing your own session id. It is
; not the end all be all of session hijacking defense, but it's a good start.
; http://php.net/session.use-only-cookies
session.use_only_cookies = 0
solved the problem.
After a long time I have fixed this bug finally.
On my localhost WAMP, the session data is not saved between page loads, because the session data is stored in a cookie, and there is no cookie domain to be set for localhost.
The solution:
'session.cookie_domain' should be set to empty string for all local domain names, not only for 'localhost' (but should not be empty for local IP addresses):
<?php
ini_set('session.cookie_domain', (strpos($_SERVER['HTTP_HOST'],'.') !== false) ? $_SERVER['HTTP_HOST'] : '');
?>
Thanks to Marcin Wiazowski who posted it here.
Faced the same problem but it was being caused by
session_regenerate_id(true);
So I just deleted it from my code.
Update to WAMP 2.5 and now the problem is solved!

Categories