PHP Session Suddenly Stopped Working For Some Pages - php

I've bumped into a strange glitch. I had no problems before but now suddenly the PHP session will only work for some pages but not others.
Here is how I use the session:
ini_set('session.save_path', realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();
if(!isset($_SESSION["account"])) {
// session does not exist
echo "<h1>session does not exist</h1>";
} else {
echo "<h1>session exists</h1>";
}
The same code does not longer work for some pages. For example I'm able to login just fine and use most of the tools for login. But when I created a new file testSession.php with the same content as shown above. It has lost the session for some reason.
I specifically used ini_set('session.save_path', realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session')); to solve a simmilar problem but now the problem is back... why?
The strange thing about all of this is that the one php script I wanted to trigger has worked before without a problem. What could be the issue here? Why does it suddnely not work for some pages/script, as far as I can tell I've never touched that part of the code, so I didn't even change anything.

I suggest to make a session.php file that you call in every page you need to access to sessions like:
session.php
ini_set('session.use_only_cookies', 1); // secure cookie
session_set_cookie_params(0,'/','localhost',true,true); // duration, path, domain, secure connection, httponly (secure js access)
session_start(); // start session
session_regenerate_id(); // regenerating for security issues
and then include this to your pages:
include 'session.php';
if(!isset($_SESSION["account"])) {
echo "<h1>session does not exist</h1>";
} else {
echo "<h1>session exists</h1>";
}

Make sure that u start session on every page. If you have it dynamicly, make sure that your require 'xxx'; is right. Then try deleting you phpsessionid in webdevelopment tools in chrome. At last, restart your local server - wamp, xampp etc.

Related

PHP create session using some functions not work [duplicate]

Here are the code of my login page where the login script checks for the authenticity of the user and then redirects to inbox page using header function.
<?php
session_start();
include_once('config.php');
$user=htmlentities(stripslashes($_POST['username']));
$password=htmlentities(stripslashes($_POST['password']));
// Some query processing on database
if(($id_user_fetched<=$id_max_fetched) && ($id_user_fetched!=0)){
$_SESSION['loggedIn'] = 'yes';
header("Location:http://xyz/inbox.php?u=$id_user_fetched");
//echo 'Login Successful';
}else{
echo 'Invalid Login';
echo'<br /> Click here to try again';
}
}else{
echo mysqli_error("Login Credentials Incorrect!");
}
?>
The inbox.php page looks like this:
<?php
session_start();
echo 'SESSION ='.$_SESSION['loggedIn'];
if($_SESSION['loggedIn'] != 'yes'){
echo $message = 'you must log in to see this page.';
//header('location:login.php');
}
//REST OF THE CODE
?>
Now with the above code, the inbox.php always shows the output:
SESSION=you must log in to see this page.
Which means that either the session variable is not being setup or the inbox.php is unable to retrieve the session variable. Where am i going wrong?
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!).
PHP session lost after redirect
I had the same issue for a while and had a very hard time figuring it out. My problem was that I had the site working for a while with the sessions working right, and then all of the sudden everything broke.
Apparently, your session_save_path(), for me it was /var/lib/php5/, needs to have correct permissions (the user running php, eg www-data needs write access to the directory). I accidentally changed it, breaking sessions completely.
Run sudo chmod -R 700 /var/lib/php5/ and then sudo chown -R www-data /var/lib/php5/ so that the php user has access to the folder.
If you use a connection script, dont forget to use session_start(); at the connection too, had some trouble before noticing that issue.
Maybe if your session path is not working properly you can try session.save_path(path/to/any folder); function as alternative path. If it works you can ask your hosting provider about default path issue.
Just talked to the hosting service, it was an issue at their end.
he said " your account session.save_path was not set as a result issue arise. I set it for you now."
And it works fine after that :)
Maybe it helps others, myself I had
session_regenerate_id(false);
I removed it and all ok!
after login was ok... ouch!
I had similar issue and with the cookie domain:
ini_set('session.cookie_domain', '.domain.com');
the domain was setup wrong so all sessions were ignored because the user cookie was never set right hope this will help someone.
The other important reason sessions can not work is playing with the session cookie settings, eg. setting session cookie lifetime to 0 or other low values because of simple mistake or by other developer for a reason.
session_set_cookie_params(0)
I encountered this issue today. the issue has to do with the $config['base_url'] . I noticed htpp://www.domain.com and http://example.com was the issue. to fix , always set your base_url to http://www.example.com
I was also facing the same problem i did the following steps to resolve the issue
I edited the file /etc/php.ini and searched the path session.save_path = "/var/lib/php/session" you have to give your session info
2 After that just changed the permission given below *chown root.apache /var/lib/php/session *
That's it. These above steps resolve my issue
Ensure values you write to your session are simple types. Complex types can cause all session changes to be dropped from memory.
I made the mistake of accidentally setting a session variable with an object value. This prevented the session from serializing and saving. The session appeared to be valid until the page refreshed.
A good way to verify this is to do a var_dump() of $_SESSION and exit() to ensure you are writing exactly what you expect.
echo '<pre>Session: ';
var_dump($_SESSION);
echo '</pre>';
exit();
In my case I could fix the issue by casting my username to string as follows:
$_SESSION['Username'] = (string)$userData->Username;
Cost: 1 nights sleep.
In my case none of above are working then I use ob_clean at the top and it worked like a charm.
ob_clean();
session_start();

Session variables and id reset at end of php script [duplicate]

Here are the code of my login page where the login script checks for the authenticity of the user and then redirects to inbox page using header function.
<?php
session_start();
include_once('config.php');
$user=htmlentities(stripslashes($_POST['username']));
$password=htmlentities(stripslashes($_POST['password']));
// Some query processing on database
if(($id_user_fetched<=$id_max_fetched) && ($id_user_fetched!=0)){
$_SESSION['loggedIn'] = 'yes';
header("Location:http://xyz/inbox.php?u=$id_user_fetched");
//echo 'Login Successful';
}else{
echo 'Invalid Login';
echo'<br /> Click here to try again';
}
}else{
echo mysqli_error("Login Credentials Incorrect!");
}
?>
The inbox.php page looks like this:
<?php
session_start();
echo 'SESSION ='.$_SESSION['loggedIn'];
if($_SESSION['loggedIn'] != 'yes'){
echo $message = 'you must log in to see this page.';
//header('location:login.php');
}
//REST OF THE CODE
?>
Now with the above code, the inbox.php always shows the output:
SESSION=you must log in to see this page.
Which means that either the session variable is not being setup or the inbox.php is unable to retrieve the session variable. Where am i going wrong?
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!).
PHP session lost after redirect
I had the same issue for a while and had a very hard time figuring it out. My problem was that I had the site working for a while with the sessions working right, and then all of the sudden everything broke.
Apparently, your session_save_path(), for me it was /var/lib/php5/, needs to have correct permissions (the user running php, eg www-data needs write access to the directory). I accidentally changed it, breaking sessions completely.
Run sudo chmod -R 700 /var/lib/php5/ and then sudo chown -R www-data /var/lib/php5/ so that the php user has access to the folder.
If you use a connection script, dont forget to use session_start(); at the connection too, had some trouble before noticing that issue.
Maybe if your session path is not working properly you can try session.save_path(path/to/any folder); function as alternative path. If it works you can ask your hosting provider about default path issue.
Just talked to the hosting service, it was an issue at their end.
he said " your account session.save_path was not set as a result issue arise. I set it for you now."
And it works fine after that :)
Maybe it helps others, myself I had
session_regenerate_id(false);
I removed it and all ok!
after login was ok... ouch!
I had similar issue and with the cookie domain:
ini_set('session.cookie_domain', '.domain.com');
the domain was setup wrong so all sessions were ignored because the user cookie was never set right hope this will help someone.
The other important reason sessions can not work is playing with the session cookie settings, eg. setting session cookie lifetime to 0 or other low values because of simple mistake or by other developer for a reason.
session_set_cookie_params(0)
I encountered this issue today. the issue has to do with the $config['base_url'] . I noticed htpp://www.domain.com and http://example.com was the issue. to fix , always set your base_url to http://www.example.com
I was also facing the same problem i did the following steps to resolve the issue
I edited the file /etc/php.ini and searched the path session.save_path = "/var/lib/php/session" you have to give your session info
2 After that just changed the permission given below *chown root.apache /var/lib/php/session *
That's it. These above steps resolve my issue
Ensure values you write to your session are simple types. Complex types can cause all session changes to be dropped from memory.
I made the mistake of accidentally setting a session variable with an object value. This prevented the session from serializing and saving. The session appeared to be valid until the page refreshed.
A good way to verify this is to do a var_dump() of $_SESSION and exit() to ensure you are writing exactly what you expect.
echo '<pre>Session: ';
var_dump($_SESSION);
echo '</pre>';
exit();
In my case I could fix the issue by casting my username to string as follows:
$_SESSION['Username'] = (string)$userData->Username;
Cost: 1 nights sleep.
In my case none of above are working then I use ob_clean at the top and it worked like a charm.
ob_clean();
session_start();

PHP: $_SESSION not working [duplicate]

Here are the code of my login page where the login script checks for the authenticity of the user and then redirects to inbox page using header function.
<?php
session_start();
include_once('config.php');
$user=htmlentities(stripslashes($_POST['username']));
$password=htmlentities(stripslashes($_POST['password']));
// Some query processing on database
if(($id_user_fetched<=$id_max_fetched) && ($id_user_fetched!=0)){
$_SESSION['loggedIn'] = 'yes';
header("Location:http://xyz/inbox.php?u=$id_user_fetched");
//echo 'Login Successful';
}else{
echo 'Invalid Login';
echo'<br /> Click here to try again';
}
}else{
echo mysqli_error("Login Credentials Incorrect!");
}
?>
The inbox.php page looks like this:
<?php
session_start();
echo 'SESSION ='.$_SESSION['loggedIn'];
if($_SESSION['loggedIn'] != 'yes'){
echo $message = 'you must log in to see this page.';
//header('location:login.php');
}
//REST OF THE CODE
?>
Now with the above code, the inbox.php always shows the output:
SESSION=you must log in to see this page.
Which means that either the session variable is not being setup or the inbox.php is unable to retrieve the session variable. Where am i going wrong?
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!).
PHP session lost after redirect
I had the same issue for a while and had a very hard time figuring it out. My problem was that I had the site working for a while with the sessions working right, and then all of the sudden everything broke.
Apparently, your session_save_path(), for me it was /var/lib/php5/, needs to have correct permissions (the user running php, eg www-data needs write access to the directory). I accidentally changed it, breaking sessions completely.
Run sudo chmod -R 700 /var/lib/php5/ and then sudo chown -R www-data /var/lib/php5/ so that the php user has access to the folder.
If you use a connection script, dont forget to use session_start(); at the connection too, had some trouble before noticing that issue.
Maybe if your session path is not working properly you can try session.save_path(path/to/any folder); function as alternative path. If it works you can ask your hosting provider about default path issue.
Just talked to the hosting service, it was an issue at their end.
he said " your account session.save_path was not set as a result issue arise. I set it for you now."
And it works fine after that :)
Maybe it helps others, myself I had
session_regenerate_id(false);
I removed it and all ok!
after login was ok... ouch!
I had similar issue and with the cookie domain:
ini_set('session.cookie_domain', '.domain.com');
the domain was setup wrong so all sessions were ignored because the user cookie was never set right hope this will help someone.
The other important reason sessions can not work is playing with the session cookie settings, eg. setting session cookie lifetime to 0 or other low values because of simple mistake or by other developer for a reason.
session_set_cookie_params(0)
I encountered this issue today. the issue has to do with the $config['base_url'] . I noticed htpp://www.domain.com and http://example.com was the issue. to fix , always set your base_url to http://www.example.com
I was also facing the same problem i did the following steps to resolve the issue
I edited the file /etc/php.ini and searched the path session.save_path = "/var/lib/php/session" you have to give your session info
2 After that just changed the permission given below *chown root.apache /var/lib/php/session *
That's it. These above steps resolve my issue
Ensure values you write to your session are simple types. Complex types can cause all session changes to be dropped from memory.
I made the mistake of accidentally setting a session variable with an object value. This prevented the session from serializing and saving. The session appeared to be valid until the page refreshed.
A good way to verify this is to do a var_dump() of $_SESSION and exit() to ensure you are writing exactly what you expect.
echo '<pre>Session: ';
var_dump($_SESSION);
echo '</pre>';
exit();
In my case I could fix the issue by casting my username to string as follows:
$_SESSION['Username'] = (string)$userData->Username;
Cost: 1 nights sleep.
In my case none of above are working then I use ob_clean at the top and it worked like a charm.
ob_clean();
session_start();

Why do I lose my PHP session on page change?

I had a login system set up that stored a session variable and checked it on each page, but then I moved to a new server.
Now any session variable I set is only available on the page it was set on. I've been searching for reasons why this could happen, and already crossed off permissions issues. Is it possible this has to do with incorrect urls? Everything else on the server appears to be working fine.
I'm running the latest version of PHP and Apache if that helps at all.
Because you probably (just assumption) have not got session_start(); throughout your other pages where required. So for example, create a page called session.php
Session.php
session_start();
if (!isset($_SESSION))
{
// Enforce logout as session is not set.
}
then:
include "session.php";
use this snippet through out your pages where your login features are required.
I've run into issues like this before. You might try setting a session id when you first start the session using session_id(), and then use the same session id before each session_start().
For example:
<?php
session_id(integer);
session_start();
?>

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

Categories