I've been thinking about this for a while and I was wondering if anyone would be able to help me figure this out. I have a website, www.domain.com/page that I'm working on. The page also has the ability of having page;var=whatever at the end.I'm trying to limit how many $_POST/$_REQUEST variables I need. Is there any way to keep a session variable active only while I'm on /page so that if a user goes to /page;var=whatever the session variable is still around but not if they go to /anotherPage? Thanks!
An easy solution would be this:
session_start();
$uri = parse_url($_SERVER['REQUEST_URI']);
if (isset($_SESSION['page']) && $_SESSION['page'] != $uri['path']) {
// We went to a new page
unset($_SESSION['var']);
}
// Remember our current page.
$_SESSION['page'] = $uri['path'];
Related
I have a page, login.php, that processes a username and password and if successful it sets session variables and then redirects the user to home.php. The relevant part of login.php is here:
if ($pwdHash == $storedpass) {
$success = true;
$sessionStatus = session_status();
if ($sessionStatus !== PHP_SESSION_ACTIVE) {
session_start();
}
$_SESSION['user_id'] = $user;
$_SESSION['logged_in'] = true;
session_write_close();
header('Location: http://www.examplesite.com/home.php');
header("HTTP/1.1 303 See Other");
die("redirecting");
}
Then home.php tries to collect the session variable
$sessionStatus = session_status();
if ($sessionStatus !== PHP_SESSION_ACTIVE) {
session_start();
}
$loggedIn = $_SESSION['logged_in'];
The problem is that on the first login attempt, $_SESSION['logged_in'] is undefined and generates an error, even though login.php was successful.
Notice: Undefined index: logged_in
A var_dump of $_SESSION returns an empty array, but sessionStatus reports that the session was already started, it did not have to execute session_start.
This forces the user to log in a second time, then everything is fine. So is the redirect just happening too fast for the session variable to get set? Should I put a delay in the redirect? (and how would I do that?) Or is this something else that I'm doing wrong?
EDIT: I've checked with my host based on an answer to a similar question and confirmed that a session would never be served by more than one server and there is no need to enable sticky sessions or anything like that. I've also updated the code above based an answer offered below and some other research but the error persists.
The session is probably automatically saved when the script ends. You redirect before the script ends.
How long your script takes to really end depends very much on what other code needs to wind down. It is better to explicitly save the session.
How to do this depends on what kind of sessions you use. One type can be closed like this:
http://php.net/manual/en/function.session-write-close.php
If that's the one you're using do this:
if ($pwdHash == $storedpass) {
$success = true;
$_SESSION['user_id'] = $user;
$_SESSION['logged_in'] = true;
session_write_close();
header('Location: http://www.examplesite.com/home.php');
header("HTTP/1.1 303 See Other");
die("redirecting");
}
And the session should be available to the next page when you redirect.
If your sessions work differently, you have to adapt the code, of course. The point I'm trying to make is: Never put a delay in your code. It's unreliable, and pointless. Simply save the session before you redirect.
I have experienced the same issue while writing the session content to the database.
To make it work I have added the sleep() function before setting the session variable, just like below.
sleep(2);
$_SESSION['GUID'] = uniqid(time().rand());
It resolves the issue for me.
We have observed this issue when the page hits are frequent but if one or two users are accessing the page it works as expected.
I have encountered this same issue with a login page but none of the suggestions work for me. The only thing I've found that does work is redirecting the page to itself after 1 second and then checking the session variables to see if the login was successful...
startSession(); // assigns all the login session variables, etc.
header('Refresh: 1; URL=/[THIS_PAGE].php'); // [THIS_PAGE] = the current login page
However, this is a very inelegant solution and I don't like using it. But it "works".
This problem persists. In my case, the user login goes without a problem to the protected homepage, but clicking on a menu link causes the user to be dumped back to the login page to login again. A check on certain Session values (required for both pages) shows these are not set on going to the specific menu link (while other menu links cause no problem). The code requiring a session value is the same in all cases. Not all users experience the problem. Seems that those with less robust connections to the internet always experience this problem. Others, never.
I have been searching for hours and cant find the answer to this one.
I am trying to add the referring url to an email message (form sent by visitor on the website) so I can know what website the visitor was referred from. (part of ongoing analytic).
I am trying to set the SERVER["HTTP_REFERER"] into a session like so..
if(!isset($_SESSION["inbound"])) {
$_SESSION["inbound"] = $_SERVER["HTTP_REFERER"];
}
but the session keeps changing every time another page is loaded. I presumed putting the ! before isset would tell it that there is already a session and not to try adding it again.
I have also tried it this way (and a combinations of other ways):
if(isset($_SESSION["inbound"])) {
// do nothing
} else {
$_SESSION["inbound"] = $_SERVER["HTTP_REFERER"];
}
I am doing this in WordPress, but I dont think that should be an issue. I have used sessions in Wordpress many times before without any problems.
Any advice or help is greatly appreciated!
Thanks
Eoin
UPDATE: Have tried it like this:
function get_ref_session() {
if(!isset($_SESSION["inbound"])) {
$the_referer = $_SERVER["HTTP_REFERER"];
$_SESSION["inbound"] = $the_referer;
}
}
add_action( 'wp_head', 'get_ref_session' );
No joy this way either :(
Tried this in the plugin and in functions.php, no joy. (at the top)
function register_session(){
if( !session_id() )
session_start();
}
add_action('init','register_session');
Wordpress does not use PHP sessions by default. It directly sets cookies to manage its own sessions.
You need to include session_start(); before any header information is sent. Otherwise no session data will be saved.
How to use session in wordpress in plugin development
function register_session(){
if( !session_id() )
session_start();
}
add_action('init','register_session');
After a big more digging, turns out that its caching of the pages that are preventing the sessions from working properly..
When logged into wordpress sessions work fine, but when logged out (which all the visitors will be) they don't work.
Think im gonna have to look into doing this with cookies instead.
I'm trying to understand sessions and how some of the functions to end them work.
I've gone to different sites/and even here on SO and, well essentially, nothing is working.
I have an app I'm trying to work on and when the user logs in, I store the username like so
(not going to paste the whole code but you get the idea)
if($row == 1){
session_start();
$_SESSION['usrname'] = $login_usrname;
$_SESSION['usrpass'] = $login_usrpass;
header("Location:index.php");
exit;
}
On the index page of said app I have a check like so
session_start();
if(!isset($_SESSION['usrname']) && !isset($_SESSION['usrpass'])){
header("Location:login-acc.php");
exit;
}
And it lets them in. I check the cookies in firefoxes web dev tools and I see it being generated so I'm going to say "its working" so far.
Now when I want to log out, Long story short I have a logout link that takes them to a page that's supposed to clear all session data and redirect them to the login page. When I'm testing the app and I click the logout link, I get redirected to the login page but when i go back and click the "index page" link. it lets me right in.
In the logout file, trying to FORCE the issue in overkill lol, I have this and nothing seems to work.
unset($_SESSION['usrname']);
unset($_SESSION['usrpass']);
session_unset();
$_SESSION = array();
session_destroy();
setcookie('PHPSESSID', '', time()-3600,'/', '', 0, 0);
header("Location:login-acc.php");
exit;
It redirects me to the login page but again, when I manually go to index page it lets me right in. Or after being redirected to the login page, I hit the "back" button and lets me right in as well.
If I then go into FF Web developer tools app and delete all cookies etc, and navigate to the index page, then it locks me out.
As you can see above ive tried multiple things and in the end, I threw them all together which should do something. My question is since I've put in ALL those functions to try and delete/unset/remove in general the session, what else can I do? I'm a bit lost as to how its supposed to work.
Can someone steer me in the right direction?
You are missing a session_start() at the top of your logout page. It's trying to modify a session that doesn't exist!
You have to start a session in order to end a session. I recommend taking a look at...
http://php.about.com/od/advancedphp/ss/php_sessions_3.htm
// you have to open the session to be able to modify or remove it
session_start();
// to change a variable, just overwrite it
$_SESSION['size']='large';
//you can remove a single variable in the session
unset($_SESSION['shape']);
// or this would remove all the variables in the session, but not the session itself
session_unset();
// this would destroy the session variables
session_destroy();
Whenever I go to a page i.e. login page or any other page, I want to save the name of the page in a $_SESSION variable.
login page:
<?php
session_start();
$_SESSION['page'] = 'login.htm';
?>
It works only for the login page and doesnt overwrite in other pages for e.g. home page:
<?php
session_start();
$_SESSION['page'] = "home.htm";
?>
I need the sesssion variable 'page' to hold the last page I was, can anyone help please?
Why not just use $_SERVER['HTTP_REFERER']? This will give you the previous page in PHP, without having to add anything to sessions.
when you navigate to a new page first retrive the saved "back" variable (and use it in a back link/breadcrumbs or something), and then overwrite the sessions "back" variable with the curent page, to have it ready for the next move =)
If all you need is default "back" functionality you should let the browser handle it.
If what you want is something to be used as a breadcrumb following some internal order (or path in a tree) my advice is to let each page "know" the path that leads to it.
If you really need to know from what page the user came from save it to a previous variable before you write over the current variable.
// Make sure user didnt just refresh the page
if ($_SESSION["current"] !== "currentPage.php") {
$_SESSION["previous"] = $_SESSION["current"];
$_SESSION["current"] = "currentPage.php";
}
You're using different keys.. 'page' and 'back'.
I have several domains pointed to the same php script.
Upon visit I want to redirect the user do a random domain of those, but only one time.
To achieve this, I set a session variable, redirect and check for that variable.
My code is this:
session_start();
if($_SESSION['seen'] != 1) {
$_SESSION['seen'] = 1;
header("Location: ".$randomurl);
}
So it should only redirect 1 time if the user has never seen the page because afterwards the session variable would contain 1 and it would not redirect.
However this is redirecting me about 5 times till it stops on a page and I can't explain why.
Does anybody have a clue?
try:
if(isset($_SESSION['seen']) && $_SESSION['seen']!= 1) {
....
}
<?php
session_start();
if ( !isset( $_SESSION["valid_user"]) )
{ header("location:domain");
}