I have a 'loginStatus' session variable that gets set on the first page load. I have an if/else to echo 'setting for the first time' comments to the browser when this 'loginStatus' is being set for the very first time. The 'setting for the first time' NEVER APPEARS! I have cleared the cache, I have tried navigating to the index.php page in a browser window outside of my Netbeans development environment -- doesn't matter. It's as if the session is staying alive permanently on my localhost web server.
Here is the code that detects for the un-initialized 'loginStatus' session variable for the first time the page is loaded and creates/initilizes the session variable just once.
if ( isset($_SESSION['loginStatus']))
{
// we get here ONLY if the 'loginStatus' session variable has already been
// created for this user's session.
$_SESSION['loginStatus'] = "loginStatus already set!";
echo '<br />Just set the loginStatus to: ' . $_SESSION['loginStatus'] . '<br /><br />';
}
else
{
// we only get here the first time this is sent by the server
// to the user's browser -- so we need to create the 'loginStatus' session
// variable because the user just came to our site
// and has not yet logged in.
$_SESSION['loginStatus'] = "First-time initialization of loginStatus";
echo '<br />Just set the loginStatus for the first time!<br /><br />';
}
I never see in the browser window "Just set the loginStatus for the first time!"
All I see in the browser window is: "Just set the loginStatus to: loginStatus already set!"
In other words -- isset() is wrongly returning true the very first time my page loads!
I see NO justification for a session variable that is magically already there when I first load the page in the browser!
Although I have loaded the above page several times tonight while writing the code, it was my understanding that when you leave the final page the session gets destroyed. So why is my $_SESSION['loginStatus'] variable hanging around like a relative who has worn out their welcome?
Session get destroyed when and by the rules set to it (to the session GC) in the php.ini file.This does not happen necessarily when you close the browser or browse to other pages.
Read the session manual in php.net and set the session rules the best way that fits you.
For example, on high security sites, I give the session a time out of few minutes. Means, if the user does no action that makes a request to the server within that time limit, the session will expire.
not sure,
but it may because you have save this values in your cookies,
try to clear cookies, and reload the page
Related
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?
I have cpanel based centos server.
I am facing issue of session variable not available through out the pages.
I checked all server setting but unable to get idea what i missed out.
<?php
session_start();
// index.php
echo "session id = " .session_id();
$_SESSION["username"] = "Niraj";
echo '<br />Lets see if session available in page 2 -> page 2';
if (!is_writable(session_save_path())) {
echo '<br><br><br><br>Session path "'.session_save_path().'" is not writable for PHP!';
}
else
{
echo '<br><br><br><br>Session path "'.session_save_path().'" is writable for PHP!';
}
?>
Output of above index.php as under:
session id = 5f59e48f328ef72fda877c8a9f7a07ca
Lets see if session available in page 2 -> page 2
Session path "/var/tmp" is writable for PHP!
If i refresh page, than session id remain same.
Code of page2.php as under:
<?php
session_start();
//page2.php
echo "session id = " .session_id();
echo "<br> Username = " . $_SESSION["username"];
?>
Output of page2.php as under:
session id =d99088ca0027a483301746e02282662c
Username =
Problem is Username doesn't output any session value. Temporary directory is writable and browser support cookies.
I marked that when click on page2.php, it will shows new value in session id, is it okay or session id should remain same across all pages?
I tried everything and put lots of effords since last 2 days,
same code working fine with other windows server and session id remain same until i close browser.
Thanks
session_id() must remain the same for you to query data which was set to that session id. The session id (dependent on lifetime value) will stay with you until the browser closes. I suspect that your browser is blocking session cookies which is causing PHP to regenerate a new ID each time the page loads. Download a new browser which you havent used before and test the theory and let me know how you get on.
You can check the global session cookie values and see what the lifetime is set to if you wish but I bet its the browser (0 == Lifetime -> until browser closes).
var_dump(session_get_cookie_params());
http://php.net/manual/en/function.session-get-cookie-params.php
Also....
You could just disable any plugins you have especially ones which stop ad's like Adblocker etc...
Have you seen anything strange occurring to the session files in /var/tmp? Could the server be deleting them?
MediaTemple Grid servers seem to have issues with sessions when they save to the tmp folder. I understand you may not be using MediaTemple, but their DV servers run CentOS so it could have something to do with the OS.
https://mediatemple.net/community/products/grid/204643480/why-am-i-experiencing-session-errors
The symptom of interest they list is "General problems with sessions not seeming to be carried across web requests." Their solution is to get session files out of the tmp folder and store them somewhere else by setting session.save_path in php.ini and restarting apache.
I am trying to use session_id() on some php pages, but the id changes between every file and it changes everytime i refresh the page. I placed the following script which should increment on ever reload, but it does not.
session_start();
if (!isset($_SESSION['hits'])) $_SESSION['hits'] = 0;
++$_SESSION['hits'];
echo '<p>Session hits: ', $_SESSION['hits'], '</p>';
echo '<p>Refresh the page or click <a href="', $_SERVER['PHP_SELF'],
'">here</a>.';
In my php.ini file, I have cookies turned on as well as set my save_path tp '/tmp'.
In the actual folder, there are session files... so i know it is not a file writing issue. I have also ensured that every file is utf-8 with bom to ensure consistency.
If there are any other solutions you can think of, please help me solve this. It is driving me insane.
Thanks!!!
The 3 possibilities I can think of for your situation are:
How are you calling session_id()? Include that code in your question. If you're calling it with any arguments it will override the session ID to whatever argument you passed.
Are cookies enabled in your browser? The session ID is sent to the browser as a cookie.
Are you calling session_destroy() at any point? This will delete the session data from the server and cause a new session to be started on subsequent pageviews.
That is because you are creating a new session every time you refresh the page. You must enclose your session start statement in a if.
if(session_id() == ''){
session_start();
}
How to include both the page counter and the last accessed time of the web page in one cookie? So that each time When I retrieve cookie information, it gives me both the details.
<?php
$inTwoMonths=60*60*24*60+time();
setcookie('lastVisit',date("G:i - m/d/y"),$inTwoMonths);
if(isset($_COOKIE['lastVisit']))
{
$visit=$_COOKIE['lastVisit'];
echo "Your last visit was - ".$visit;
}
else
echo "You've got some stale cookies!";
?>
Your example is never gonna work. When setting the cookie, the actual value is not available for PHP. PHP sends the cookie to the browser along with the rest of the headers and only the next time you load the page, the cookie is send from the browser to the server and has a value retrievable for PHP.
But to answer your question:
A cookie can store an array. See example 3 of the manual.
You could do something like:
$page_counter = 371;
$last_visit = date("G:i - m/d/y");
setcookie('lastVisit[count]',$page_counter,$inTwoMonths);
setcookie('lastVisit[visit]',$last_visit,$inTwoMonths);
On the next load, you can then do
$cookie_value=$_COOKIE['lastVisit'];
echo $cookie_value['count'];
echo $cookie_value['visit'];
I need to destroy a session when user leave from a particular page. I use session_destroy() on the end of the page but its not feasible for me because my page has pagination. My page is: abc.php?page=1 or abc.php?page=2 or abc.php?page=3.
So, I need to destroy a session when a user leaves from abc.php page. How can I do it without using a cookie?
Doing something when the user navigates away from a page is the wrong approach because you don't know if the user will navigate to a whole different page (say contact.php for the sake of the argument) or he/she will just go to the next page of abc.php and, as Borealid pointed out, you can't do it without JS. Instead, you could simply add a check and see if the user comes from abc.php:
First, in your abc.php file set a unique variable in the $_SESSION array which will act as a mark that the user has been on this page:
$_SESSION['previous'] = basename($_SERVER['PHP_SELF']);
Then, add this on all pages, before any output to check if the user is coming from abc.php:
if (isset($_SESSION['previous'])) {
if (basename($_SERVER['PHP_SELF']) != $_SESSION['previous']) {
session_destroy();
### or alternatively, you can use this for specific variables:
### unset($_SESSION['varname']);
}
}
This way you will destroy the session (or specific variables) only if the user is coming from abc.php and the current page is a different one.
I hope I was able to clearly explain this.
To trigger when the user actually leaves the page, you must use Javascript to send an asynchronous request back to the server. There's no way for the server to magically know the user has "left" a page.
See http://hideit.siteexperts.com/forums/viewConverse.asp?d_id=20684&Sort=0 .
I had a similar issue but mine was on a page reload I wanted variables that I had printed to be destroyed. It was for my login for my web design class I was making error feed back for if user put in a bad username or password. I could get the error to display but if I hit refresh page they errors would just stay there. I found that by just setting the variable to nothing after it printed would kill it. Take a look at what i did:
<p>To access my website please Login:</p>
<form name='login' action="./PHP_html/PHP/login.php" method='post'>
Username: <input type='text' name='username' /><div><?php print $_SESSION['baduser']; $_SESSION['baduser'] = "";?></div><br />
<div style="padding-left: 4px">Password: <input type='password' name='password' /><div><?php print $_SESSION['badpass']; $_SESSION['badpass'] = "";?></div></div>
<input type='submit' value='Login' /> or you can Register
I don't know if this helps at all but it worked for me.
Also, thanks to all you that post on sites like this to help those of us who are still learning.
For a particular page you need to destroy the session, then unset the all session variable
using
unset($_SESSION['varname']);
For the whole site you can use session_destroy();
I solve the problem.First take the current url then chk the page stay on current url.if page is not in the current url then destroy the session.
$url = "http" . ((!empty($_SERVER['HTTPS'])) ? "s" : "") . "://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$page_name="abc.php";
if (!preg_match("/$page_name/",$url))
{
session_destroy();
}
But this code should be used on another pages.Because http is a stateless processes so no way to find when a user leave the page.
You can't tell when a user navigates away from the page, it's simply not possible in any reliable manner.
The best you can do is exploit how cookies work. When starting a session, you're sending a cookie to the client which identifies the client on each subsequent visit, and hence activates the associated session. It is up to the client to send this identification on subsequent visits, and it's up to the client to "forget" his identification.
You can instruct the client to only send the cookie for certain pages, and you can instruct him to forget the cookie when closing the browser (with a lifetime of 0). This can be set using session_set_cookie_params.
Other than that, you can simply ignore the session parameters on pages where they don't matter. You can delete the session (or certain values of it) after some time of inactivity when you assume the client has left.
Borealid deserves credit for pointing to the most elegant solution.
A more kludgey solution is to keep an iframe on the page that is pointed to another "monitor" page which is set to refresh every few seconds. This can be done without JavaScript using:
<meta http-equiv="refresh" content="10">
This refreshes the monitor page every 10 seconds. When this happens, the monitor page can record the time (overwriting the previously recorded time) and session ID on the server somewhere (DB or file).
Then you would have to create a cronjob that checks the file/DB for any sessions that are more than 10~12 seconds old and delete them manually. The session data is usually stored in a directory (specified by your PHP config) in a file named sess_the-session-ID. You could use a PHP function like this:
function delete_session($sessId) {
$sessionPath = session_save_path();
// you'll want to change the directory separator if it's a windows server
$sessFile = "$sessionPath/sess_$sessId";
if (file_exists($sessFile) && unlink($sessFile)) return true;
return false;
}