Googlebots and session - php

I have a section of a website that sets a session variable. On another section of the site, if that variable is set, then it redirects them back to where the part of the site that set the variable.
<?php
//page1:
session_start();
$_SESSION['pg1']=true;
//page2
if ($_SESSION['pg1']===true)
{
header('Location: http://www.mysite.com/?page=1&WELCOME_BACK');
}
?>
I think this behaves like I want by defalut, but I want Googlebot to be able to visit page1, then visit page2 without being re-directed. Can anyone confirm that?
What I mean is, does a visit from Googlebot (or other SEs in general) generate a session that persists between pageviews.
(I know, if someone closes their browser they can come back to page2, but it's okay if they do that.)

Googlebot does not accept cookies from strangers, so there will be no session variables when it visits your second page. This will result in what you want to happen here, but keep it also in mind for future reference.

if ($_SESSION['pg1'] == true && strpos($_SERVER['HTTP_USER_AGENT'],'Googlebot') === false)
{
}
List of user agent strings: http://www.useragentstring.com/pages/useragentstring.php

Related

How to destroy session in PHP when browser back button is clicked?

I have read many related question here but seems not solve my problem. How to destroy session in PHP when user clicked at the browser back button.
Example, current page is home.php, when back button is clicked, it will go to index.php. So should be session will by destroy.
I trying both options. But still not destroy the session.
First Option (home.php)
<?php
session_start();
if (isset($_SESSION)) {
session_destroy();
}
?>
Second Option (index.php) This is not practical.
<script language="javascript" type="text/javascript">
window.history.forward();
</script>
If you want a reliable way to clear all values of any current session you can use this on the loading of any page where you want to remove session data:
<?php
session_start();
if ($criteria_for_session_deletion === true) {
$_SESSION = []; // _SESSION is now an empty array
}
This will remove any value from the superglobal. It will not change the identity of the superglobal, but that shouldn't be important if the variable is now empty.
It is unclear from your question but you may be having overlap issues with browser caching of the outputted HTML page. Please clarify exactly what you're trying to delete?
Clicking on a "back button" is a very problematical way of solving this concept and we really need some clarification from you as to what's actually going on.
If you have a user who needs to have session data removed then you should check this in PHP on a script before any outout is sent to the browser, and then triggering the above code when required.
You maybe should have a "validity check" script included in each page so every time one of these pages is loaded your "check script" is called, and deletes the session data when the deletion criteria is met.
Why do you want to destroy session? That is just irritating. I have seen such implementations in government/bank websites and it pretty much sucks.
Rather you should redirect the user to dashboard if the user is logged in.
This doesn't directly answer OP's question but is a better way.
Something like this:
if (isset($_SESSION)) {
header('Location: <dashboard-page>');
exit;
}

PHP if(isset($_COOKIE['visitor']) not working with page refreshs

I'm working on a simple cookie notice that appears on first visit only and again but only until 30 days has gone by.
The problem that I'm having is the page that is setting the cookie for the entire domain keeps receiving the notice once I go to a different page and then back again, unless I do a hard refresh (CTRL+F5) the notice just won't go away.
In my header.php I have:
$value = 'first_visit';
setcookie("visitor", $value);
setcookie("visitor", $value, time()+604800);
setcookie("visitor", $value, time()+604800, "/", ".example.com");
if(isset($_COOKIE['visitor']) && ($_COOKIE['visitor'] == true)){
// do nothing
} else {
echo '<div id="cookie">By continuing to use our Site, you are agreeing to the placement of cookies on your computer by us and our third party service providers.</div>';
}
So the idea of the code is that the user visits the site and then the page triggers a creation of a cookie, the value of this cookie is not important since the code will simply check to see if one exists, the first time the visitor visits the site, it does not exist therefore they it echo's else, going to other pages other than the page I just visited does // nothing as intended but if I go back to the page that triggered the creation, its still else, unless I do a hard page refresh.
I have also tried:
<?php
if(isset($_COOKIE['visitor']) && ($_COOKIE['visitor'] == true)){
// DO NOTHING
} else {
$value = 'first_visit';
setcookie("visitor", $value, time()+604800, "/");
echo '<div id="cookie">By continuing to use our Site, you are agreeing to the placement of cookies on your computer by us and our third party service providers</div>';
}
?>
I don't think there's anything wrong with your code - ie it's working as expected based on the code. I just don't think you see what the code is actually doing. You say the cookie is eventually set, but you are setting the cookie on a page, moving on, then using back button and getting to a page with that message again. This is likely browser cache, and likely confirmed as you say a hard refresh fixes this.
It seems odd the way you are doing all of this. All I can get from your question and code is you require:
First visit - user sees message and cookie is set
Consequent visits/pages after this - user doesn't see message because cookie is set
The only way you can avoid the browser back messing this up for you is to do a redirect after you set the cookie (eg $_SERVER['PHP_SELF']). but then you can't use the same file to show the message as by then the cookie will be set.
You should rethink this and handle the whole thing differently, but as it stands, with the code you have presented, all I can suggest setting a session.
header.php
session_start();
if (!isset($_COOKIE['visitor']) || ($_COOKIE['visitor'] != true)) {
$value = 'first_visit';
setcookie("visitor", $value, time() + 604800, "/", ".example.com");
$SESSION['displayMessage'] = true;
} else {
if (isset($SESSION['displayMessage'])) {
unset($SESSION['displayMessage']);
}
}
if (isset($SESSION['displayMessage'])) {
echo '<div id="cookie">By continuing to use our Site, you are agreeing to the placement of cookies on your computer by us and our third party service providers.</div>';
}
On the first visit the cookie won't be set so it's set and a session is set, as the session is set it'll show the message. Then on any other page load as the cookie is set the ELSE will kick in and session is unset, and therefore the message is not shown.
(I reverted your cookie checks so you don't have that awful pointless // do nothing ;) )
The above code is very clunky, and I cried a bit writing it. Again, I advise you step back and rethink how you are handling all of this to make it more robust. Separate out your requirements into different files, better use functions, and then call things as and when you need them based on other things being set :)

PHP ending sessions(different ways) i dont understand

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

Destroy PHP session on page leaving

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

Get original URL referer with PHP?

I am using $_SERVER['HTTP_REFERER']; to get the referer Url. It works as expected until the user clicks another page and the referer changes to the last page.
How do I store the original referring Url?
Store it either in a cookie (if it's acceptable for your situation), or in a session variable.
session_start();
if ( !isset( $_SESSION["origURL"] ) )
$_SESSION["origURL"] = $_SERVER["HTTP_REFERER"];
As Johnathan Suggested, you would either want to save it in a cookie or a session.
The easier way would be to use a Session variable.
session_start();
if(!isset($_SESSION['org_referer']))
{
$_SESSION['org_referer'] = $_SERVER['HTTP_REFERER'];
}
Put that at the top of the page, and you will always be able to access the first referer that the site visitor was directed by.
Store it in a cookie that only lasts for the current browsing session
Using Cookie as a repository of reference page is much better in most cases, as cookies will keep referrer until the browser is closed (and will keep it even if browser tab is closed), so in case if user left the page open, let's say before weekends, and returned to it after a couple of days, your session will probably be expired, but cookies are still will be there.
Put that code at the begin of a page (before any html output, as cookies will be properly set only before any echo/print):
if(!isset($_COOKIE['origin_ref']))
{
setcookie('origin_ref', $_SERVER['HTTP_REFERER']);
}
Then you can access it later:
$var = $_COOKIE['origin_ref'];
And to addition to what #pcp suggested about escaping $_SERVER['HTTP_REFERER'], when using cookie, you may also want to escape $_COOKIE['origin_ref'] on each request.

Categories