Get original URL referer with PHP? - 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.

Related

How to store an external HTTP_REFERER in a cookie in PHP for later retrieval?

I would like to have a PHP code to do the following:
User comes to my website from a link in an external website, in other words, the HTTP_REFERER is not from my own domain.
Save this HTTP_REFERER in a cookie
In another part of my website I will check to see if this cookie is present and include the saved referer with the user profile.
Saving cookies is pretty easy (see PHP Cookies for details).
if(isset($_SERVER['HTTP_REFERER'])) {
setcookie("externalRefer", $_SERVER['HTTP_REFERER'], time()+3600);
}
Retrieving is just as easy:
if (isset($_COOKIE['externalRefer'])) {
echo $_COOKIE['externalRefer'];
}

Set cookie, nothing is being shown

This is taken directly from w3's website. I may not be understanding cookies correctly, but why is nothing displaying?
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
echo $_COOKIE["user"];
Your cookie will only be accessible when you refresh the page or navigate to a new one.
When your script loads, the HTML header fields for that page have already been set. The page will need to be rendered again (another HTTP transaction) before your cookie is available for use. Check PHP's documentation:
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
check that your browser allows localhost / 127.x.x.x cookies or not ? if it allows then refresh the page. If you are using Google Chrome then you can see all browser cookies from here : chrome://settings/cookies navigate to localhost / 127.x.x.x to see your code has put cookies or not !
The variable $_COOKIE[] representates the state at the start of the script. That means that you have to wait on the next page request to see the variable. You could also add your variable manually to the global cookie variable $_COOKIE['user] = 'Alex Porter'; but the problem is that you are not sure that the browser really accepted the cookie.

php session pass with setcookie and unset

i have a strange problem, when i use setcookie in PHP with session, while my browser is open, everything work fine, but when I close it, then I can't pass $_SESSION from page to another page!
in login page I have:
$_SESSION['name'] = $_POST['name'];
$_SESSION['pass'] = $_POST['pass'];
$life=2592000;//1 month
setcookie(session_name(),session_id(),time()+$life);
header("location:administrator/");
die();
I used session_start(); in every page on top of them, also I used this code for logout:
session_start();
unset($_SESSION['name']);
unset($_SESSION['pass']);
session_destroy();
header("location:../");
an important note is when I checked browser cookies, before closing browser there are tow cookie and their contents value is exactly same like each other, one expire at the end of session but another expire one month latter, which I like to be, but then I close browser and return back, there are tow cookie but with different values! which I think case problem and session variables don't pass from page to page.
Apart from the problem mentioned by #Matt (you may need some custom mechanism to restore or reinstantinate session using cookies), keep in mind that using mod_rewrite or actual directories messes with cookies path! To make sure the cookie is available when and where you need it, add additional parameter / (PHP setcookie(), $path parameter)

Googlebots and session

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

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

Categories