Setting $_SESSION doesn't work on localhost using XAMPP - php

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

Related

PHP - /tmp permission error

Basically, I have an .htaccess file, with php_value session.auto_start set to 1.
So my session will start in any file.
However, now I have a script in my /functions folder, but it gives an error about the permissions of the /tmp, resulting in "Failed to write session data", though it doesn't use, start or do anything with the session.
Yet this produces an error, and to me, it looks like it cannot find the /tmp folder, which I do have. Files directly in my root folder (/) don't have this a problem.
I also tried setting the permissions of /tmp to 777, to no avail.
Thanks in advance
The error I'm getting
Warning: Unknown: open(/tmp/sess_cfed7db100fd58b62eaca2a519ebaf7a, O_RDWR) failed: Permission denied (13) in Unknown on line 0
Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/tmp) in Unknown on line 0
The script itself:
<?php
define ('INCLUDE_CHECK',true);
require('connect.php'); //This file doesn't use any sessions as well
if(isset($_POST['signupemail'])){
$email = mysqli_real_escape_string($link, $_POST['signupemail']);
$thearray = mysqli_fetch_array(mysqli_query($link, "SELECT COUNT(*) FROM `users` WHERE email=\"".$email."\""));
if($thearray[0] > 0){
echo '"This emailaddress is already in use"';
exit;
}
echo "true";
} else if(isset($_POST['uname'])){
if(!preg_match('/^[a-zA-Z0-9_-]{3,16}$/ ',$_POST['uname'])){
echo '"<small>Please only use alphanumeric characters, underscores and hyphens</small>"';
exit;
}
$uname = mysqli_real_escape_string($link, $_POST['uname']);
$thearray = mysqli_fetch_array(mysqli_query($link, "SELECT COUNT(*) FROM `users` WHERE uname=\"".$uname."\""));
$forbiddennames = array(1 => 'super-user','superuser', 'root', 'admin', 'administrator', 'system', 'website', 'site', 'owner', 'manager', 'founder','moderator');
if(in_array(strtolower($_POST['uname']), $forbiddennames)) {
echo '"'.$_POST['uname'].' is a forbidden username"';
exit;
}
if($thearray[0] > 0){
echo '"This username is already in use, please choose another"';
exit;
}
echo "true";
}
?>
I get the error when I just browse manually to my script, so without any $_POST parameters set. I use this script to verify one's email and/or password, and when checking, it stops, not knowing what to do with the result (gotten by AJAX).
I think i remember some php.ini setting that prevents access to files that are not in the webserver's directory tree. I don't know if that applies to files that are generated internally by php, though.
If you're running on Red Hat Enterprise linux, or some derivative like CentOs or Scientific Linux, it might also be a problem with selinux. Check if the problem goes away if you set selinux to permissive (sudo setenforce Permissive). If that "fixes" the problem, think twice about leaving selinux in Permissive mode, especially if your server is reachable from the internet, better learn about selinux and relabeling.
Uhm, it turned out to be browser-related.
When I tested it in FireFox, no problem.
In Google Chrome, big problem.
I don't know what it was, but after deleting the cache, cookies, everything from my site, it worked perfectly. Seemed like it was searching for an old session.

php session work on localhost but not on vps webserver

<?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);

Do I need to modify my Bluehost php.ini file? Header function not working on remote server

This block of code shown below using a php header redirect works locally, but not on my Bluehost server:
if ($_POST['submit']=='No')
{
$url ='Location: index.php?id='.$id.'&page='.$page;
header($url);
exit;
}
When the server gets to this block of code, absolutely nothing happens. No error, no warning, just a blank page. The page that my form submit redirects to isn't supposed to do anything except reroute the user to the relevant page.
I'm pretty dang positive it has nothing to do with the common problem of including HTML before the redirect (since it works locally). Therefore I suspect it has something to do with differences between my php.ini files. I've pulled up PHPinfo() for both servers, and my local server has a module named mod_headers while my Bluehost server has none. I think this potentially could be the problem, although normally my Bluehost has no problems using header redirects, except in this one instance.
So I suspect the problem has something to do with my ini file, but I don't know exactly what.
What makes this problem even stranger is that there are other blocks of code which work just fine, for instance
if(!empty($_POST['id']))
{
$id = htmlentities(strip_tags($_POST['id']));
$sql = "UPDATE entries SET title=?, entry=? WHERE id=? LIMIT 1";
$stmt = $db->prepare($sql);
$stmt->execute(array($title,$entry,$id));
$stmt->closeCursor();
$url= 'Location: ../index.php?id='.$id.'&page='.$page;
header($url);
exit;
}
works just great.
I had the same problem that it works fine on XAMPP but not on bluehost or 1&1.
PHP documentation says there should be no output before calling the header function.
http://php.net/manual/en/function.header.php
In my case there was a space before the opening <?PHP which made the header function not work.
This should help to solve the problem.
The quesiton remains though: why does it work on XAMPP and not on the servers of bluehost, 1&1, etc?
(since I use firefox for both tests - it is definitely not a browser issue)
I just had this problem. I realized that I was using an editor that was inserting a BOM at the beginning of the file. This BOM character is virtually invisible to most editors but will stop PHP's header from firing because it does count as ouput. Here is more information on the BOM character:
http://en.wikipedia.org/wiki/Byte_order_mark
I was using notepad++ and was able to disable this BOM by using these directions:
Go to Settings > Preferences > New Document/Default Directory
Changed Encoding to UTF-8 without BOM
The HTTP standard requires that the URL in the Location: directive is an absolute URL. You can't just use index.php for that redirect. You'll need to use:
header("Location: http://example.com/index.php");
Some browsers ignore the standard and allow relative URLs.
I faced the same problem when running moving my Wordpress blog to Bluehost.
The solution was to change output_buffering option in php.ini
Look what at my config along with the explanation of this option:
; Output buffering allows you to send header lines (including cookies) even
; after you send body content, at the price of slowing PHP's output layer a
; bit. You can enable output buffering during runtime by calling the output
; buffering functions. You can also enable output buffering for all files by
; setting this directive to On. If you wish to limit the size of the buffer
; to a certain size - you can use a maximum number of bytes instead of 'On', as
; a value for this directive (e.g., output_buffering=4096).
output_buffering = 4096

Session Start Failure

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.

How to troubleshoot PHP session file empty issue?

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);
?>

Categories