<?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);
Related
I have multiple system running on PHP 5.3 that are 15-10 years old, I can't go on those and change anything.
Problem is: some of those system are using PHP register_globals = on that is depreciate on PHP 5.3 and doesn't even exist in PHP 5.4 (http://php.net/manual/en/security.globals.php).
I am developing a new system and would like to turn PHP register_globals = off But I can't because all those old system that NEEDS it.
So I thought about dynamically changing the register_globals to off in my script using string ini_set ( string $varname , string $newvalue ) but the documentation (http://php.net/manual/en/function.ini-set.php) baffles me a bit:
Sets the value of the given configuration option. The configuration option will keep this new value during the script's execution, and will be restored at the script's ending.
Does that mean that if I have two script running at the same time lets say... One of my old system that really needs register_globals = on and my new system that use ini_set() to register_globals = off that the old script will be running with the newly changed setting? Or will it keep the setting in my PHP.ini file and the new system will run on the ini_set() configuration?
--EDIT--
After some test (see code below) #Jacob was right and it seems PHP create a context for each script and that ini_set() only change the configuration of the script its in.
TestWithIni_Set.php
<?php
ini_set('register_globals', '0');
$i = 0;
while(true)
{
if($i == 0)
{
phpinfo();
}
$i++;
}
?>
TestWithoutIni_Set.php
<?php
phpinfo();
?>
So I ran TestWithIni_Set.php first, then will TestWithIni_Set.php was executing (the infinite while loop) I ran TestWithoutIni_Set.php.
Unfortunatly, it seams like I can't change register_globals value with ini_set(). I tried the following:
//Knowing that ini_set() parameters are strings I tried those anyway.
ini_set('register_globals', '0');
ini_set('register_globals', 0);
ini_set('register_globals', 'off');
ini_set('register_globals', 'Off');
ini_set('register_globals', false);
ini_set('register_globals', 'false');
Then to make sure I didn't had something wrong in my code I tried:
ini_set('log_errors', '0');
Just to see if it would work and it did. Then value of log_errors for the script with ini_set() was off and the value of log_errors for the script without ini_set() was on.
But now I have a different problem.
How can I change the value of register_globals for only the running script if I can't change it using ini_set()?
I added a .user.ini file to my new system dir with the only line being register_globals=off.
I also went and uncomment the following line in my PHP.ini file:
user_ini.filename = ".user.ini"
I also made sure only a local user had the rights to make changes to that dir. So somebody couldn't go and upload a new user define .ini file for my server within this dir.
For exemple: IIS user can only read the file in this dir and can't add/modify/remove any file.
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
I am new to coding in php and also getting the environment set up on my local computer.
Here's the current setup configuration - I have installed wamp server version 2.2 which has the following - Apache 2.4.2, php 5.4.3, mysql 5.5.24
There is a very simple php code that i had written -
<?
mysql_connect("localhost","user","password");
mysql_select_db("mydbase");
$result = mysql_query("SELECT * FROM names WHERE ID LIKE '2'");
while($r=mysql_fetch_array($result))
{
$id = $r["id"];
$name = $r["name"];
}//close while
?>
Even a simple echo is not working. the output is blank. the same code works on the web server. It has the same user name, password and the tables were exported (from the webserver) and imported (into the local mysql).
The phpinfo() page shows the following -
display_errors - on - on
error_log - no value - no value
The php.ini file shows the following -
; display_errors
; Default Value: On
; Development Value: On
; Production Value: Off
and
;error_log = php_errors.log
; Log errors to syslog (Event Log on NT, not valid in Windows 95).
;error_log = syslog
error_log = c:/wamp/logs/php_error.log
The error logs are empty.
When i look at the source in the browser,
for the page online - it shows the output
for the page on the local computer - it just shows the php code
Could anyone please let me know what the problem could be? It seems like that there are some settings that i have messed up. But, i did not change anything - it is a regular installation and no custom settings were added.
Your script doesn't work, but your phpinfo page works? Check short_open_tag in your php.ini. Or modify your script and change your opening <? to <?php. If that works, you found the problem!
this happened to me too, try enabling the mime_module of apache
If, on info.php file creation with
<?php phpinfo(); ?>
You actully get that result, check if your webserver is configured to use php as script files:
Check inside httpd.conf for these lines and alter them if necessary:
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>
Restart server and try to run the script again.
I tested this script on another server and it worked fine. Do I have to set my php.ini file? And how?
<?php
ini_set('allow_url_fopen', 1);
if (!isset($_GET['url'])) {
exit();
}
echo file_get_contents($_GET['url']);
?>
From the PHP Manual on allow_url_fopen
Note: This setting can only be set in php.ini due to security reasons.
Open the PHP.ini file with an editor and change the setting accordingly. If this on shared hosting and you do not have access to the PHP.ini contact your hosting service and ask them if they could change the setting.
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);
?>