FInding out referring page (php) - php

At my work I often need to figure out where our traffic comes from. We buy google ads and that traffic gets identified by a query string in the url. (mywebsite.com/?x="google_ad_group_4").
On every page I include some sessions stuff that sets $_SESSION['x'] to $_GET['x'] if $_GET['x'] is there. If there is no $_GET['x'] I go through some other options to see where they came from and set that in $_SESSION['x']:
$refurl = parse_url($_SERVER['HTTP_REFERER']);
$query = $refurl['query'];
parse_str($query, $result);
if (isset($result['q'])&& strstr($_SERVER['HTTP_REFERER'],'google')) {
$_SESSION['x'] = 'G-'.str_replace('\\"',"X",$result['q']);
}elseif (isset($result['p'])&& strstr($_SERVER['HTTP_REFERER'],'yahoo')) {
$_SESSION['x'] = 'Y-'.$result['p'];
//took out bing, aol, ask etc in the name of brevity
}else{
if ($refurl['host']){
$_SESSION['x'] = $_SESSION['x'].'_ref-'.$refurl['host'];
}
}
This way I can append the search query that brought the user to the site and what search engine they used. I log the incoming $_SESSION['x']'s.
Many users are coming in with $_SESSION['x']'s of "_ref-mywebsite.com" which doesn't make sense, if they were coming from my own domain, they'd have already had a $_SESSION['x'] set on whatever page they'd been on. Is this because they have their browser's security turned up high or something?
Am I missing something obvious? Is there a smarter way to do this?

You can get the referrer like this
echo $_SERVER['HTTP_REFERER'];
But as mentioned in comment, it can easily be manipulated.

Unless the client (the browser) passes you the "HTTP_REFERER" in the heading, you won't get it. And that depends on the site they come from.
I don't know what your workflow is like, but one thing you can do is get it with JavaScript and pass it to your PHP script. Hope this helps.

I think that a possible scenario is:
A new visitor comes to the website with normal referrer;
He closes his browser(this clears his session cookie) with the website's tab opened;
Reopens the browser with the website restored in old tab;
Clicks on any link on the page and gets to another page with referrer from same domain and clean session.

Related

match previous url to give alternate 'cancel' button

I have a site with a normal admin and a super admin, both share some functions. A new function I am introducing is a admin serial activation. This is already implemented in normal admin and now I am trying to add same code to super-admin. If you are in normal admin or super admin you would click the serial to activate and move on to activate2.php to activate. All works well and good unless you change your mind about activating serial, in which case you would click 'back' or a 'cancel' button to return to previous screen. I currently check what the previous page was using php:
$ref = $_SERVER['HTTP_REFERER'];
The idea is to show a different return url on 'back' link and the 'cancel' button depending on if the previous page was 'super-admin-serials.php' or just 'admin-serials.php'. I tried to match 'super-admin-serials.php' in $_SERVER['HTTP_REFERER'] to deduce what the previous page was and allow the user to go back to his previous page. But the code I have put together does not work, so if anyone out there can help with this simple function it would be much appreciated. Here is the code I have so far on the independent 'activate2.php' page to cancel and return to previous:
$superpage=array('super-admin-serials.php');
$ref = $_SERVER['HTTP_REFERER'];
if (in_array($ref, $superpage)) {
echo "back (super admin)";
} else {
echo "back (normal admin)" ;
}
The HTTP referer may not just contain the name of the script it comes to, it usually includes a fully qualified URL such as http://example.com/foo/your-script.php.
Instead of observing the HTTP referer (which will be lost if they refresh the page), I suggest that you pass an argument from the first page to the second to determine where they came from, and send them back where you need.
Transparently the user will be accessing either of:
activate2.php?super=1
activate2.php
Then the following code will do what you want:
$isSuper = !empty($_GET['super']);
if ($isSuper) {
echo "back (super admin)";
} else {
echo "back (normal admin)" ;
}
I understand you have some kind of sign in feature and you cannot be logged in simultaneously with two different users (if that's not the case, just make sure you aren't running an insecure site that can be easily hacked). In that case you should already have that information on the server so it's both unnecessary and unreliable to gather it from client-side. So code would look like this:
if ($_SESSION['is_super']) {
echo 'back (super admin)';
} else {
echo 'back (normal admin)';
}
(Please note I've also removed double quotes, which served no other purpose than making code harder to write and read.)
In any case, you must be aware that HTTP_REFERER:
Will get lost if you add extra steps (e.g. show form errors to get them corrected)
May not be there at all (some proxies and security programs strip it)
Will often include extra stuff that make a simple string comparison fail, like GET parameters (and it's of course a full URL)
If you opt for it anyway you may want to have a look at parse_url() as starting point.

PHP get previous page url after redirect

I want to have a navigation bar that tells the user where they just came from.
Example: Homepage -> Post
But if they are in their posts manager and click on a post, I want it to say
Posts manager -> Post
I read that $_SERVER['HTTP_REFERER'] is not good enough to get the full url so that's not useful as I want the navigation bar all clickable
Any help is much appreciated!
I believe what you want is called breadcrumbs.
What to use for navigation chain storage is actually up to you. You might use even $_SERVER['HTTP_REFERER'] if you want, but that'd be unreliable as it's client-side. Usual way to store such chain is actual URI or session.
For example, you have such URI: http://www.example.com/post_manager/post
Then you can iterate through explode("/", $_SERVER["REQUEST_URI"]) to get each step.
That's basic explanation to guide you to a right direction. You can google alot of samples and snippets using keyword breadcrumbs.
On the topic of saving last visited location (the way to determine wether abonent came from manager or homepage): you can use session's variables to do that. Here's an example:
This way you can set a variable on your homepage:
<?php
session_start();
$_SESSION['previous_location'] = 'homepage';
?>
And then you just access it from another page:
<?php
$previous_location = $_SESSION['previous_location'];
?>
It's important to set session.save_path in your PHP configuration file or your sessions might get lost.
You could do it on the client side if you use the Javascript document.referrer property. However, a better solution may be to use the global session array.
if (!isset($_SESSION['referrer'])) {
$_SESSION['referrer'] = $current_uri;
} else {
$previous_uri = $_SESSION['referrer'];
$_SESSION['referrer'] = $current_uri;
}
The best solution IMO is to save the location into session, every time the user goes to a 'meaningful' page (that you want to be able to navigate back to via this feature), then simply use this array of, say, last 2 visited pages to pull up all the information. Simple and effective.
<?php
session_start();
$_SESSION['user_interactions'][] = $_SERVER['HTTP_REFERER'];
// get previous
$previous_page = end($_SESSION['user_interactions']);
// list all user interactions
foreach($_SESSION['user_interactions'] as $key => $value){
echo $value;
if(count($_SESSION['user_interactions'])-1 != $key) echo ">";
}
?>

Check last visited between two php pages

Is there some sort of PHP code that allows me figure out which of the two pages was last visited.
Here is why i need it.
I have 3 pages called:
user-management.php, manage-membership.php and manage-user.php
There are two ways of getting to manage-user.php. One is to click on the name of the user in user-management.php and the other is to click on the membership account holder in membership-management. Both user-management and membership-management are completely different pages so please don't tell me to merge them to make it easier, because it won't get easier.
What i want to do is track where i'm coming from.
For example, if i'm going to manage-user.php from user-management.php, when all the editing is done, i want it to redirect back to user-management.php, and the same for membership-management.
How do i check to see which of the two pages I came from and redirect back to those pages accordingly?
Have each of your scripts record their name in the $_SESSION, so you're keeping track of where you came from:
user-management.php:
$_SESSION['came_from'] = 'user-management.php';
and then in your manage-user.php script:
Back
This is more reliable than using the HTTP referer, because not everyone sends refers, or sends the ACTUAL referer.
you could use $_SERVER['HTTP_REFERER'];
But this is not so safe, better store the page in a session and
check it then.
session_start();
...
$_SESSION['log'][] = $_SERVER['PHP_SELF'];
...
if ($_SESSION['log'][count($_SESSION['log'])-1] == "xxx") {
do code...
}
Tried this? -> $_SERVER["HTTP_REFERER"]
You can read more from this: http://www.electrictoolbox.com/php-http-referer-variable/
You could use $_SERVER['HTTP_REFERER']; but the user can also set their browser to not send the referer header. You could also do something like this:
At beginning of page:
session_start();
$lastVisited = $_SESSION['last_visited'];
At end:
$_SESSION['last_visited'] = $thisPagename;

How to access offsite referer (and first page visited on site) via PHP on Wordpress site

I'm trying to get three things into a hidden form field in a Wordpress page:
The last "offsite" page visited before someone visited any page on my site (e.g., quite possibly a Google page)
The first page they visited on my site
The last page on my site before they went to the form page
The third one is easy (just use ), but the first two are giving me problems.
I'm trying to save #1 and #2 by using session variables, so that on every page, in the header, I have the following code:
<?php
session_start();
if (! isset($_SESSION['offsite_referer'])) {
$_SESSION['offsite_referer'] = $_SERVER['HTTP_REFERER'];
}
if (! isset($_SESSION['first_page'])) {
$_SESSION['first_page'] = $_SERVER['REQUEST_URI'];
}
?>
Then further down I have, as test code (to be changed to input type=hidden etc. later):
<p>offsite_referer: <?= $_SESSION['offsite_referer'] ?></p>
<p>first_page: <?= $_SESSION['first_page'] ?></p>
(FWIW, I also have session_start() at the top of my wp-config.php. Yes, my site has register_globals turned off.)
For some reason, $_SESSION['offsite_referer'] always ends up as my home page, even when I hit the form page (/free-reports) directly via link from another site. Similarly, first_page always shows up as /
Yes, I'm clearing all my cookies etc. between attempts, to force a new session to be created.
This code used to work fine on my pre-Wordpress site, so I can only think it has something to do with WP, specifically perhaps WP's redirection (WP's mod_rewrite stuff in .htaccess)
I tried changing $_SESSION['offsite_referer'] = $_SERVER['HTTP_REFERER'] to wp_get_original_referer() but it seemed to have no effect.
Incidentally, if I access my form page (at /free-reports/) as the first page on my site (after clearing cookies etc.) and printing $_SERVER['HTTP_REFERER'], it correctly shows the last offsite page - even though $_SESSION['offsite_referer'] doesn't.
I'm pretty perplexed, and have spent a fair amount of time trying to figure it out on my own, so any help to solve this would be appreciated.
Chances are, you can't really get the referer URL since some browsers don't send that and some people disable that, but here's how you could do that and I'll give you some extra tips here:
//first of all, initialize the session
session_start();
//Now call logvisit() to log where the user is coming from
logvisit();
function logvisit() {
$_SESSION['offsite_referer'] = $_SERVER['HTTP_REFERER']);
$browser = $_SERVER['HTTP_USER_AGENT']; //Gets the browser the user is using
//If you want to test it (disable the code below if you don't want to print that information):
echo "Offsite referer: $_SESSION['offsite_referer']<br>";
echo "Browser: $browser<br>";
}
Then to destroy the session you can use unset($_SESSION['offsite_referer']);
This is how I usually do it, and it's often a tidy way to do it.
I believe scunliffe had the key to this, as I was using IE to do the testing.
It works fine now, which I attribute to actually closing and restarting IE (apparently just deleting cookies doesn't do it, as you'd think, even though that works fine in Firefox).
I also changed what I was doing slightly to just save the full in-site browse history in a session variable, rather than only first and last page on the site.
The code I ended up with was the following, which is just at the top of my theme's header.php file:
<?php
session_start();
if (! isset($_SESSION['site_history'])) {
$_SESSION['offsite_referer'] = $_SERVER['HTTP_REFERER'];
$_SESSION['site_history'] = '';
}
$_SESSION['site_history'] .= ($_SERVER['REQUEST_URI'] . ';');
?>
I originally had session_start() also in wp-config.php when I was trying to figure this out, but was able to remove it (leaving just the above code in header.php) and things still work fine.
In case anyone finds this page wanting to do something similar, I was able to access this info in my WP page by adding the following to my theme's functions.php:
function get_offsite_referer() { return $_SESSION['offsite_referer']; }
add_shortcode('offsite-referer', 'get_offsite_referer');
function get_site_history() { return $_SESSION['site_history']; }
add_shortcode('site-history', 'get_site_history');
and then to pass the info on my Wordpress page/form:
<input type="hidden" name="offsite_referer" value="[offsite-referer]" />
<input type="hidden" name="site_history" value="[site-history]" />
scunliffe, if you'd posted your comment as a "reply" I would have "accepted" it, since it was what most closely led me in the right direction, but as a comment I could only upvote it so that's what I did. Thanks!

$_SERVER['HTTP_REFERER'] shows current page

I have a tracking script that I use to save analytic data to our company database. We have quite a few websites (around 2000 domains) and PPC campaigns and the script I'm using works just fine.
I know that the $_SERVER['HTTP_REFERER'] is not 100% reliable and can be either empty or spoofed, whatever, that is a small minority of the leads we have coming in (I take this into account in my tracking script).
The problem is that although my $_SERVER['HTTP_REFERER'] var always comes back empty if I echo it out on the affected page, it is passed to the tracking script (via a $_SESSION var) as the current page URL. It's as if (note the 'as if', I know this is not the case) PHP is substituting $_SERVER['REQUEST_URI'] for $_SERVER['HTTP_REFERER'].
This is from the landing page:
$_SESSION['keywords'] = $_SERVER['HTTP_REFERER'];
require_once 'tracking.php';
$raw_query = $_SESSION['keywords'];
$key_browser = getKeywords($raw_query);
$keywords = $key_browser['keywords'];
$referer = $key_browser['referer'];
$user_agent = getBrowserOs($_SERVER['HTTP_USER_AGENT']);
$br = $user_agent['browser'];
$os = $user_agent['os'];
The tracking script is inconsequential because the variables I pass it are not altered.
if you load your script with HTML tag like <script src="mytracking.php"></script>, referer will be the same as request_uri because request_uri is the one that requests the script.
The only script that gets the referer from which user came if link is clicked is the script that responds to the request from the browser. All resources, loaded via HTML tags will have the current page as referer. Which, by the way, is often used as a protection against hot-linking of images and other resources.
Well I've found no proper solution so I've opted to use a hidden field whose value is populated with javascript's document.referrer property and simply passed that to the tracking script. Definitely works although I'm not too pleased that I couldn't find a better solution.

Categories