I have a very simple test page for PHP session.
<?php
session_start();
if (isset($_SESSIONS['views']))
{
$_SESSIONS['views'] = $_SESSIONS['pv'] + 1;
}
else
{
$_SESSIONS['views'] = 0;
}
var_dump($_SESSIONS);
?>
After refreshing the page, it always show
array
'views' => int 0
The environment is XAMPP 1.7.3. I checked phpInfo(). The session is enabled.
Session Support enabled
Registered save handlers files user sqlite
Registered serializer handlers php php_binary wddx
Directive Local Value Master Value
session.auto_start Off Off
session.bug_compat_42 On On
When the page is accessed, there is session file sess_lnrk7ttpai8187v9q6iok74p20 created in my "D:\xampp\tmp" folder. But the content is empty.
With Firebug, I can see cookies about the session.
Cookie PHPSESSID=lnrk7ttpai8187v9q6iok74p20
It seems session data is not flushed to files.
Is there any way or direction to trouble shoot this issue?
Thanks.
BTW, it is $_SESSION not $_SESSIONS.
Hence why it isn't saving the data.
The variable you need to set is called $_SESSION not $_SESSIONS
Heres what I did ...
Install sqlite for php if older than php5 (installed and enabled by default since php5).
In your php.ini (for the location see phpinfo() or run>php -i) change the line ..
session.save_handler = files
to
session.save_handler = sqlite
Then in the same file (php.ini) make sure NOTICES are turned on
error_reporting = E_ALL
restart apache if you changed php.ini
/etc/init.d/apache2 restart
Now you will be getting a sensible error message most likely revealing you dont have correct permissions to your session.save_path so ...
Find out your web services user and group unless known.
There are several ways to do so but I placed this line temporarily in my php code ...
print_r(posix_getpwuid(posix_getuid()));
And I found that user www-data and group www-data were set for this web user by my ispconfig3.
Make a session directory on your web path (probably /var/www) for the web user.
sudo mkdir /var/www/whatever;
sudo chown <user_from_last_step>:<group_from_last_step> /var/www/whatever
eg>sudo chown www-data:www-data /var/www/whatever
Again in your php.ini file make sure session.save_path is commented out, something like ...
;session.save_path = /var/lib/php5
but not
session.save_path = /var/lib/php5
restart apache if you edited php.ini
Now go to your php code (Many have a SetEnv.php ish type script which does some global stuff and is imported by all files) and add the following line BEFORE you call session_start() ...
ini_set('session.save_path', '0;0750;/var/www/whatever');
Note that we set session.save_path in your code rather than in php.ini to help keep it secure, so to replace 'whatever' with something inventive would be useful.
By now it should appear to be working, but not quite, it doesent work accross ajax requests for some reason that I dont care about related to sqlite ... so ...
Go back to your php.ini file and change the line ...
session.save_handler = sqlite
back to
session.save_handler = files.
restart apache
Fixed :) Hopefully :|
use $_SESSION and check it by print_r($_SESSION);
<?php
session_start();
if (isset($_SESSION['views']))
{
$_SESSION['views'] = $_SESSION['pv'] + 1;
}
else
{
$_SESSION['views'] = 0;
}
echo "<pre>";
print_r($_SESSION);
?>
Related
I know there are similar other questions here, but none of them solved my problem.
The problem: I'm setting data into $_SESSION, but in upcoming calls it is appearing as empty.
What I did to try solving it?
Make sure to run an up-to-date version of PHP
Make sure to know which php.ini is used
Log status of $_SESSION before and after setting it
Set various variables as suggested in other questions and forums
Here below I provide all the info I could supply, and hoping somebody will be able to suggest a solution!
I have installed PHP on my Mac using brew install php
I am running it locally for software development using this command:
php -S localhost:8099 -d display_errors=on -t .
[Tue Nov 17 23:12:55 2020] PHP 7.4.11 Development Server (http://localhost:8099) started
I'm calling session_start(); at the beginning of my script.
I am setting values into $_SESSION, but it is always empty when I am testing it in the following calls:
$ses = json_encode($_SESSION);
site_log("before: {$ses}");
session_regenerate_id();
$_SESSION["upath"] = 'XXXXXX';
$ses = json_encode($_SESSION);
site_log("after: {$ses}");
The result is always the same (while I'm expecting to see it on first call but not for the following calls):
20201118_040124_484 before: []
20201118_040124_485 after: {"upath":"XXXXXX"}
I was trying to follow many ideas from web forums:
Verify which is the INI file:
php -i | grep 'Configuration File'
>Configuration File (php.ini) Path => /usr/local/etc/php/7.4
>Loaded Configuration File => /usr/local/etc/php/7.4/php.ini
I was setting various INI file variables:
session.save_path = "/Users/myuser/Prog/MyApp/sessions"
+
chmod 777 /Users/myuser/Prog/MyApp/sessions
+
session.use_cookies = 1
+
session.cookie_secure = 0
But the result is still the same. Any idea please?
The following link points to the result of calling phpinfo(): link
So finally I have found a solution.
It is based on information provided here: Session cookie not being set
As #deceze was commenting correctly to my question, the first steps to debug such problem are these:
Check whether session files are created in the save_path folder (in my case: yes)
Use the dev-tools of the browser to see if cookies are set for the site (in my case: no)
So the actual problem is: why cookies are not set?
The solution:
Add an entry to alias 127.0.0.1 as a 'dot com' name. This is what I did:
# for Mac! see linked answer for other platforms
sudo vi /private/etc/hosts
# add this line:
127.0.0.1 mylocal.com
Activate the local php server for this domain (from the site root folder):
php -S mylocal.com:8099 -d display_errors=on -t .
Load the site from the php server. I'm using Brackets, and I had to open the menu: File -> Project Settings and set the live preview base URL to be:
http://mylocal.com:8099/
Some variables in the INI file might need to be set too, as already detailed in the question above
Hoping this info will help to others!
I started to use memcached for storing session files, but Session doesn't work and apache sends response too slow. How can I solve the problem?
Modifications in php.in are:
;session.save_handler = files
session.save_handler = memcached
session.save_path = "tcp://127.0.0.1:11211?persistent=1&weight=1&timeout=1&retry_interval=15"
I solved the problem, Solution is connection url without tcp://
,so session.save_path should be
session.save_path = "127.0.0.1:11211?persistent=1&weight=1&timeout=1&retry_interval=15"
read this page:
http://www.php.net/manual/en/memcached.sessions.php
you should modify php.ini like that
session.save_handler = memcached
Change memcached to memcache
Maybe Helpful for you
Else
That Check For Server Permissions And Check For Charset of Your PHP script And
Put this code:
in being:
<?php
ob_start ();
?>
at the end:
<?php
ob_flush ();
?>
I set my session like so in my PHP code : $_SESSION['user_id'] = $login; and this seems to work fine whilst uploaded to my server and carries across different pages, however when I am testing the website on my local machine the session seems to become immediately unset after leaving the script where it is set.
I am testing on my local machine using XAMPP and exactly the same code.
I am not sure why this problem is occurring and would greatly appreciate any helpful answer.
Example that is not working:
$_SESSION['user_id'] = $login;
echo '<META HTTP-EQUIV="refresh" content="0;URL=../home.php">';
EDIT 1:
Here is my entire function in which I log in (it's part of the class):
public function loggingIn(){
session_start();
$db = new Database('localhost','root','','userdata');
$userFunctions = new Users($db);
$username = $_POST['usernameInput'];
$password = $_POST['passwordInput'];
if(empty($username) || empty($password)){
$this->errors['u&p'] = 'Please Enter Your Username AND Password';
$this->printE();
} elseif($userFunctions->user_exists($username)===false){
$this->errors['nm'] = 'That Username/Password Combination Is Not Valid';
$this->printE();
} else {
$login = $userFunctions->login($username, $password);
if($login === false){
$this->errors['nm'] = 'That Username/Password Combination Is Not Valid';
echo 'Login Failed!';
} else {
if(!$userFunctions->economyTableExistsForUser($login)){
$userFunctions->createEconomyTableForUser($login);
}
if(!$userFunctions->schoolTableExistsForUser($login)) {
$userFunctions->createSchoolTableForUser($login);
}
$_SESSION['user_id'] = $login;
echo $_SESSION['user_id']; // working fine
header('Location: ../home.php');
}
}
}
Let's guess that your home machine is not having:
session.autostart = On
in your php.ini, while your other machine obviously is.
Make sure that you have set in your PHP code:
session_start();
PHP: session_start - Manual
If you don't, then your session is not started, unless my first conjecture is true.
Besides, you must check for you PHP version on your localhost and settings in php.ini. Make sure that the directory where you store you session files is writeable and session files do really exist.
EDIT 1:
You better use PHP solution for redirection:
header("Location: /");
exit();
EDIT 2:
PHP has functions that modify HTTP headers. Some of them:
header
session_start
setcookie
EDIT 3:
Line-breaks and spaces could be a problem but there are also invisible character sequences which can cause Warning: Cannot modify header information, like the UTF-8 BOM (Byte-Order-Mark).
Try re-saving your file making sure that it's saved just as UTF-8 (no BOM).
EDIT 4:
To properly debug your code make sure that PHP displays all warning and notices. Run it before session start:
ini_set('display_errors', -1);
EDIT 5:
You must also check session.gc_maxlifetime setting:
session.gc_maxlifetime
session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and cleaned up. Garbage collection occurs during session start.
EDIT 6:
To view white-spaces in Sublime Text, edit the settings:
// Set to "none" to turn off drawing white space, "selection" to draw only the
// white space within the selection, and "all" to draw all white space
"draw_white_space": "selection",
You can set it in Preferences->Settings Default. If you edit your user settings Preferences->Settings - User and add the line as per below:
{
"font_size": 10,
"draw_white_space": "all"
}
Also make sure it shows all other special characters to properly debug your code!
EDIT 7:
Finally try adding session_write_close(); right before redirecting.
EDIT 8:
Set in your PHP file, before session_start();, session.save_path = "/home/username/tmp"; directive.
Create tmp dir outside of public_html. Make sure that tmp dir has chmod 770 and created with the same user/group privileges . Run ls -lsa in your home dir to check if the new directory has the same user/group as other directories, like public_html for instance. If not, make sure changing permissions as root on tmp by running chown username:groupname /home/username/tmp.
A quick update on this. I found this response very useful, however, please note that in my installation of XAMPP, the php.ini entry for session.autostart=On, is slightly different. I found the following:
; Initialize session on request startup.
; http://php.net/session.auto-start
session.auto_start=0
I changed this to:
; Initialize session on request startup.
; http://php.net/session.auto-start
session.auto_start=1
Make sure session cookies are enabled in php.ini (xamp\php\php.ini).
session.use_cookies=1
In your php.ini check:
variables_order contains the letter S
Check that session.save_path exists and is writeable by the user under which PHP is running.
If you are using PHP embedded within .htm/.html documents, you need to ensure that Apache can process them appropriately. This is done by editing the httpd.conf and adding the line
AddType application/x-httpd-php .html .htm
to the section <IfModule mime_module>
I was fighting with this problem but solve...
In your /opt/lampp/etc/php.ini try to change this line:
session.save_path = "/var/lib/php/session"
For this:
session.save_path = "/opt/lampp/var/session"
Note: Maybe you need to create the folder "session" in /opt/lampp/var
Open php.ini
change session.auto_start with "1"
"Stop" Apache if running
"Save" php.ini
"Start" Apache
Session Issue Fixed in Xampp 7.1.6 with following Changes in php.ini
Line #1403 set:
session.auto_start = 1
I had similar problems live site working Xampp not.
The trick in my case was to disable the two lines below.
header('Set-Cookie: same-site-cookie=huis; SameSite=Lax');
header('Set-Cookie: cross-site-cookie=stijl; SameSite=None; Secure');
So check anything that modifies something regarding coockies is my advise.
Please check your "session.cookie_path" in php ini. By default it is "session.cookie_path=/"
Enable session cookies in php.ini (C:\xamp\php\php.ini).
CHANGE
session.use_cookies=0
TO
session.use_cookies=1
AND remember to restart xampp
<?php
session_start();
if(isset($_SESSION["counter"])){
echo session_id()." ".$_SESSION["counter"];
$_SESSION["counter"]++;
}
else{
$_SESSION["counter"]=0;
echo "start counter";
}
?>
It's just a basic example code for session. It working find of my PC using XAMPP. But it doesn't work at all when I put it in to my vps webserver. The out put only include"start counter" and never changed whatever I refresh the page. I checked php.ini both on XAMPP and vps. variables_order = "GPCS" request_order = "GP" register_globals = Off session.save_handler = files Above configurations are same on XAMPP and vps.
It can be due to the reason that your session expires too fast on another server. Start by making sure you're setting the session variable correctly. It's possible that sessions either aren't enabled or aren't configured correctly in the php.ini file on your server.
You can try putting this in front of the file to see any errors. When you see the error you can figure out where you have gone wrong.
error_reporting(E_ALL);
ini_set('display_errors', 1);
This is not your average session failed to start question, there is no whitespace, i have not called it in another file etc.
Im currently working on an application as I have started to build my session library, now when I call session_start I get the following error:
A session had already been started - ignoring session_start()
For those who wish to see the source: https://github.com/AdminSpot/ASFramework/blob/master/system/libraries/session.php
This usually means that the session.autostart directive is set to 1, but that's the thing.. it's not, it's set to 0 and I have verified this by doing the following:
Search my entire system for php.ini* files, checked them
Executed the following command php --ini amd validated the ini files
executed the following command php -i | grep session.auto_start. which responded with session.auto_start => Off => Off
Checked the PHPInfo page, see image below
Checked the php.ini files for cgi
There is no htaccess files on nginx
grep -lir "session_start" * only shows my library file
Restarting FastCGI, Nginx and the entire server
I have created a basic test script to test where i have just called session start on it's own.
The phpinfo() call stats the active php.ini is /etc/php5/cgi/php.ini so after running cat /etc/php5/cgi/php.ini | grep session.auto_start I get session.auto_start = 0, so it disabled, Could it be NGinx ?
Has anyone got any idea what's going on, some server information below:
PHP: PHP 5.3.5-1ubuntu7.2 with Suhosin-Patch
MySQL: Ver 14.14 Distrib 5.1.54, for debian-linux-gnu (i686) using readline 6.2
Nginx: Version: nginx/0.8.54
PHPInfo screen:
My first guess would be that you have an auto-prepend file or an .htaccess which is modifying the settings in the meanwhile.
You can use ini_get to retrieve the value of session.auto_start and auto_prepend_file to confirm. phpinfo() should work too.
Edit
Could it be that your session library is being instantiated twice? Since return $this->session_started is an instance variable, that could cause issues. What happens if you set that to a class-level variable?
Side note:
You also have this return $this->session_started = true; at the end of the start() method. It shouldn't matter, but it looks funny.
How about .htaccess containing a php_value session.auto_start 1? PHP on the command line would totally ignore settings overrides in .htaccess files. Remember that commandline PHP and web-based PHP have completely different .ini files in most standard configurations, so checking via command line is a waste of time.
I'd suggest having your script do a phpinfo() immediately before one of your session_start calls and check what the effective settings are there.
And anyway you can just verify if a session has already started or not.
if (!isset($_SESSION)) {
session_start();
}
http://php.net/manual/en/function.session-start.php#90007
Check and see if you are being passed a session cookie. May help you narrow it down.