$_SESSION variables last one page load - php

Here's the code
<?php
print_r(session_get_cookie_params());
session_set_cookie_params(3600, "/", "mydomain.com");
When I refresh the page, the above parameters are not saved
session_start();
var_dump($_SESSION);
$_SESSION['name'] = "name";
When I refresh the page, the above variable is not saved
var_dump($_SESSION);
print_r(session_get_cookie_params());
However, both variable and parameters are correctly displayed on first page load.
?>
The first var_dump ALWAYS returns an empty array, the second successfully returns the "name" within it.
$_SESSION variables only ever last one page load.
I have tried naming the session, adding a (long) timeout, linking to a different page, but $_SESSION variables only ever last one page load.
Must this be a problem with the server?

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!';
}
This is from a previous post : PHP Session not Saving

if you use memcache/redis/mysql session storage backend, it can be down. Is there any errors shown? Try to enable error reporting in PHP.ini and rerun the code.
Probably you have put some html output before session_start()
and this prevents from setting the session.

Related

PHP session variable set on page (verified) does not exist after redirect or page change

PHP 7.1.7 on Windows Server 2008 Enterprise
... I noticed there were 5 other questions here just like this with no answer. I'm getting frustrated trying to do something that's always been so easy to accomplish in other languages for me. I just want to set a session variable and then read it on another page after a redirect. That should be simple basic functionality and I do not get why I've been sitting here for 2 hours trying everything I can think of and I still can't figure it out.
Each page of my application starts with: session_start();
I have a form edit processing page I'm starting with, where on a successful edit, the user is redirected back to the index page. Before the redirect, I'm setting a session variable ('success'). At this point, the session variable is set. If I comment out the header and exit() lines and echo the session["success"] variable.
$_SESSION["success"] = "The record was inserted successfully.";
header( 'Location: index.php');
exit();
}
Register Globals does not exist in my PHP.ini file (register_globals). I tried adding "register_globals=0;" to the PHP.ini file and restarting the server but I still doid not see a "register_globals" listing on the PHP info page.
No matter what I have tried, after the redirect to the index.php page, that session variable does not exist after the redirect ($_SESSION["success"]). I'm staying inside the same domain (same folder on the server really)
After setting the session variable ('success') and proving that it is set by echoing it on the edit proccessing page followed by an exit, I can not figure out how to get the session variable to persist after a redirect or page change:
If I try and echo that 'success' session variable after a redirect, I get this:
Notice: Undefined index: success
I'm not understanding why this is so difficult? What else could I try?
Thanks for any help.
Test whether the session cookie is set properly.
$_SESSION["success"] = "The record was inserted successfully.";
// header( 'Location: index.php');
echo session_name() .': '.session_id(); // print session cookie name & value
echo '<pre>' . print_r(session_get_cookie_params() ) . '</pre>';
exit();
What do you see? Open your browser's dev tools and look at cookies set when the server echoes the info above. If there is no cookie with the name (typically PHPSESSID) and session ID value above, then either your browser is not accepting cookies or the server isn't setting them. Either one will break cookie-based sessions.
If these seem to work ok, then re-establish your redirect. On the next page (index.php in your example), take a look at which cookies are received:
// Notice: this won't work on the page setting the cookie.
// Cookie should show up on the next page
echo '<pre>' . print_r($_COOKIE) . '</pre>';
Does the session id cookie exist?
If all this works, I would then look at whether PHP is actually storing session files properly. Session data is serialized and saved to files in a folder on the server's hard drive. Take a look at your php.ini, where you should see something like:
session.save_handler = files
session.use_cookies = 1
; where on server the files should be stored. the folder should be
; readable/writeable to the PHP process. Maybe '/tmp'?
session.save_path =
If you edit your php.ini, remember to restart the server.
Update
From your comments, everything seems to be setup correctly. Remove all other code. and just have this:
page1.php
<?php
session_start();
$_SESSION = []; //start with an empty array
$_SESSION['success']= 'record saved';
$_SESSION['id'] = session_id();
header('Location: index.php');
exit;
index.php
<?php
session_start();
var_dump($_SESSION);
if(isset($_SESSION, $_SESSION['id'])):
echo 'Session ids ' . ($_SESSION['id']===session_id()? 'match' : 'do not match');
endif;
What gets var-dumped in index.php after you get redirected from page1.php?

Session cookie is reset to default at the end of the script

I made a simple registration page, which after validation, adds a unique identifier to the session id to identify the user and also sets a session variable 'UID' to a custom value. Then the script redirects to a new page.
$_SESSION['UID'] = $id;
session_id($sessID);
echo session_id();
session_write_close();
header("Location: https://localhost/AccountWebsite/landing.php");
exit();
?>
The landing page is supposed to be accessible only by members (i.e. those with a special unique session id set by my script), and that functionality wasn't working. So to check why, at the moment I allow anyone to access the page and their session id is echoed, and so is the 'UID' session variable.
<?php
session_start();
echo session_id()."\n";
echo $_SESSION['UID'];
?>
Now, when I echo the id it isn't the one I set myself. It is the generic PHP one, and the variable doesn't exist. During debugging, I commented out the redirect in the registration script, and instead had it echo the session id that it had just set. The echoed id is correct (obviously since it's echoed in the script it's set in), although when I enter the cookie manager on Firefox, it displays the session id as the generic php one, which means the session is reset when the first script ends and not between sessions.
Make sure session_start(); is called before any sessions are being
called. So a safe bet would be to put it at the beginning of your
page, immediately after the opening php tag before anything else.
Also ensure there are no whitespaces/tabs before the opening php
tag.
After the header redirect, end the current script using exit(); (Others have also suggested session_write_close(); and
session_regenerate_id(true), you can try those as well, but I'd use
exit();)
Make sure cookies are enabled in the browser you are using to test it on.
Ensure register_globals is off, you can check this on the php.ini file and also using phpinfo(). Refer to this as to how to turn it off.
Make sure you didn't delete or empty the session
Make sure the key in your $_SESSION superglobal array is not overwritten anywhere
Make sure you redirect to the same domain. So redirecting from a www.yourdomain.com to yourdomain.com doesn't carry the session
forward.
Make sure your file extension is .php (it happens!)
I have done all of the above from dayuloli's answer on this post
and have been debugging all day. Please help, why does the session not keep the id and variable values I set to it by the end of the script and sccross the whole server?
Additional info: I tried another example folder (on htdocs) where one page sets a variable and the other echoes it, and it worked.
You don't need to set a session_id unless you want multiple sessions. If you do specify a session_id, you need to call session_start() afterwards to start using it and submit the cookie into the client's browser.
Beyond that explanation, you need to use session_start() at the top of any script that requires sessions.
From http://php.net/manual/en/function.session-id.php:
session_id() needs to be called before session_start()
session_id() will always send a new cookie when session_start() is
called

PHP Centos : Session not able to store

Hi Today I am facing one strange Problem
After login validation I am storing the user name in session and redirecting it to some other page .
Validation page .
if (mysql_num_rows($sqlQuery) == 1) {
session_start();
$_SESSION['username'] = $login;
print $_SESSION['username'];
header("Location: dialout.php");
}
.
on dialout.php I am trying to print session like
var_dump($_SESSION);
But it doesn't print anything .
some googling I found that problem might be in writing the session directory .
So to check that I wrote one script .
print session_save_path();
if (!is_writable(session_save_path())) {
echo 'Session path "'.session_save_path().'" is not writable for PHP!';
}
else{
echo "writable -------------";
}
From above script I am getting writable.
Just wondering why my I am unable to access the session on dialout.php page
In your Validation page,the following code should be at the top of the file, as first line in your code.
session_start();
It should be included in every page if you want to use session variable.
First, carry out these usual checks:
Make sure session_start(); is called before any sessions are being
called. So a safe bet would be to put it at the beginning of your
page, immediately after the opening
After the header redirect, end the current script using exit();
(Others have also suggested session_write_close(); and
session_regenerate_id(true), you can try those as well, but I'd use
exit();)
Make sure cookies are enabled in the browser you are using to test
it on.
Ensure register_globals is off, you can check this on the php.ini
file and also using phpinfo(). Refer to this as to how to
turn it off.
Make sure you didn't delete or empty the session
Make sure the key in your $_SESSION superglobal array is not
overwritten anywhere
Make sure you redirect to the same domain. So redirecting from a
www.yourdomain.com to yourdomain.com doesn't carry the session
forward.
Make sure your file extension is .php (it happens!)
can all be found here: PHP session lost after redirect
Call session_start function in dialout.php befor accessing session variable like this :
session_start();
var_dump($_SESSION);

Using PHP session variable to keep user logged into website

I want to assign a value to a session variable when a user logs into a website. I read that I must explicitly start a session at the top of my pages in order to do this. So I inserted:
if (!isset($_SESSION)){
session_start();
echo "started";
}
The first thing I notice is that "started" is displayed every time I reload my page. Is that expected behavior? I would assume the second time I load the page, the session should already be there, therefore "started" would not display.
Further down in my page, I have:
$_SESSION['id']=2;
echo "<p>Your session ID is: " . $_SESSION['id'] . "</p>";
That correctly displays the ID in the "echo" statement. So even after assigning a value to a session variable, when I reload the page, it puts "started" at the top.
Am I doing something wrong? Thank you!
That is expected behaviour, you need to call session_start() before any output is sent to the browser every time the page is loaded, which is why your echo is happening every time. You if statement in this case is a little unnecessary and you should just simply call it without the if.
session_start();
For example, a $_SESSION variable will never be accessible unless you call session_start(), despite the fact that it will exist in the browser's session. Calling session_start() simply allows you to access that superglobal array.
You need to put your session_start() at the top of the file.
Otherwise you won't be able to use the $_SESSION array.

declaring session variables php

Is it not mandatory to use session_start() before using any session variables in PHP?
I tried the following piece of code without declaring session_start() at the beginning, it worked fine.
So, now I'm confused. Please help !!!!
Also, I did not use any $_POST or $_GET to pass $uname to home.php, but still how does it work? If we use include 'home.php' then does it treat login.php and home.php as same page?
// code login.php//
<?
require_once 'db_connect.php';
if (isset($_SESSION ['user_id']) && !empty($_SESSION ['user_id']))
{
$u_name = $_SESSION['user_name'];
include 'home.php';
}
else
{
//some stmt
}
?>
/*******home.php file ****/
<?php
require_once 'dbconnect.php';
$_SESSION['username'] = $u_name;
//echo $_SESSION['username'];
//blah blah
?>
You definitely need it, if session.autostart is not set in php.ini. But you would probably know that then.
Do you not call it in db_connect.php? Also, I'm pretty sure you wouldn't get any errors, the session would just be empty.
If you include a file via php, Session keeps active (as any others variables set too). If you would access this file as new request, you would need to set session_start().
This behaviour is because include and require act like moving the code of the included file into the current one, as you would have typed the code into one single file.
Plus: you don't need to require dbconnect.php twice.
edit: you asked about both files used as the same page - the page is the output given after the whole php code is done. The page itself doesn't care about how many files internally are used for generating it.
Use the session_start () is obligatory for every session in php. Being passed through a variable values ​​is not necessary to make POST or GET the same, since there is already the case the value increment. If not ouver value in the same session is null or blank, if you open the page in the same way the condition is wrong.
(!Isset($_SESSION ['user_id']) &&!​Is_Null($_SESSION['user_id']))
isset to check if empty this need! before, IF(!isset($_SESSION['user_id']) and in the second case would be to check if it is not null and void, for a session either exists or does not exist and if a value is set inesistente is null. So correct view is this: is_null($_SESSION ['user_id'])
Importantly, in the login page does not include but redirect to the page. in the case with a header.
Or could do everything in a single page, but it would not be legal to display on a page called login page. The default would be the index, ie if the login stay within a folder, you place it inside the index page and the address of the folder.
The reason for the session can still open is that sometimes the webserver does not realize that erased part of the code and loads of it from the system cache.

Categories