How to echo the last visited page in PHP? - php

I don't know is there is a PHP function like the ones that start with $_SERVER['']
That tell user which page he came from, on his current page.
ex. If I was browsing foo.com?id=abc then went to foo.com?id=efg, I need the current page to tell me that I came directly from foo.com?id=abc
I need this code badly, so any help is appreciated.

It is $_SERVER['HTTP_REFERER']. But it is filled only if browser did so. Otherwise you need to track user yourself (i.e. by storing last page in session)

The $_SERVER variables should not be relied upon to provide accurate answers. You should use PHP Sessions to track what page they come from, and simply update it everytime they go to a new page. Something along the lines of:
session_start();
if(!empty($_SESSION['visited_pages'])) {
$_SESSION['visited_pages']['prev'] = $_SESSION['visited_pages']['current'];
}else {
$_SESSION['visited_pages']['prev'] = 'No previous page';
}
$_SESSION['visited_pages']['current'] = $_SERVER['REQUEST_URI'];
Then to access the previous page, access the: $_SESSION['visited_pages']['prev']

The HTTP_REFERRER gives address of the page that requested the file. For example an image on a page is a separate request, and this request has a $_SERVER['HTTP_REFERRER'] set to the page.
I don't think browsers allow servers to access history. It can be done with JavaScript, though only a back button can be provided, the url cannot be accessed easily. Though it can be achieved using a simple css and javascript trick by accessing the computed color to a link.

Yes, and this is not only in PHP, this is a part of the HTTP protocol specification, Use:
$_SERVER['HTTP_REFERRER']

Related

If a url is redirected to another, is there a way to use the original domain in php

Noob here! This is my first post - I apologise if it's been answered already.
I can't find anything in the search!
I have a number of sites in development and want to redirect them all to a single splash page for the company that owns them.
Is there a way to determine which url it was redirected from to allow different text and contact info to be called?
I can find lots of answers about using the current url - but not one that redirected to it.
Thanks for your help!
Like Kkinsey said in the comments - The first approach I would take is starting with $_SERVER['HTTP_REFERER']
Using Referer will work most of the time. Some browsers don't send it.
Instead, add a GET parameter to your redirection URL:
header("Location: http://main-company.net/splash?from=".$website_id);
exit;
Then retrieve it on the main website, if set it will be the variable $_GET['website_id'].

How to prevent user from bookmarking URLs?

My website's webpages displays webpages by using GET to retrieve variables from a predefined URL.
For example the code on the first page: index.php
<p>next page</p>
The second page: blank.php?name1=value1&name2=value2
$name1 = $_GET['name1'] ;
$name2 = $_GET['name2'] ;
echo $name1 ;
echo $name2 ;
This way webpages are created on the spot and displayed kind of like a CMS and Iuse this method for all the webpages my site has, but if a user bookmarks a tab they will have out of date information for that webpage because that page content is contained in the URL.
EDIT: If I were to use post would their be a better way of conveying that information to the new webpage? instead of:
<form method="post" action="blank.php">
<input type="hidden" name="name1" value="value1">
<input type="submit">
</form>
Quick and dirty solution: Add a timestamp parameter to your urls, like:
<p>next page</p>
Then, on the page, check if the timestamp is older then a certain duration:
if(!isset($_GET['time']) || time() - intval($_GET['time']) > 60*60) {
header('Location: index.php');
}
$name1 = $_GET['name1'] ;
$name2 = $_GET['name2'] ;
echo htmlspecialchars($name1);
echo htmlspecialchars($name2);
So if a link is older than one hour (60 seconds times 60 minutes), it is redirected to the home page!
But this method is not very user friendly! You should better try to build your links so they never get old content when visiting!
You could prevent the user from using the keyboard shortcut for bookmarking, but I don't think there is anyway to prevent the user from bookmarking it in their browser (or writing down the URL for that matter).
You may want to look into generating the data on the page on each page load so if the user bookmarks the URL, they see the most recent information. Or if the user didn't follow a certain path to arrive at that path display a message telling them the data is out of date.
Using POST instead of GET Would resolve the issue for the most part, but I understand this may not be possible depending on the amount of code that you have already created. Another possible solution is to set Session variables to determine if that person should have access to this page or not. If they do not have access, than you send them back their landing page, profile, or even login page. I have done this by placing session variables that can only be set on one page, and then destroyed after the page is viewed, this way they cannot simply go back to the page because the session value is gone.
Sadly it is not possible to prevent people from creating bookmarks to your page, you simply need to filter out who can see(edit or access) it.
You are essentially talking about user sessions only during which all the variables would make sense. Even using POST doesn't solve the problem. In the extreme case one can make a POST request (or search engine may do) and misinterpret the retrieved result. I would suggest to append a sessionid as many other websites do and on the backend to control the valid timeframe. This way you have better control of your website functionality and user experience. Whether a session has expired or not should depend on your business logic, not GET/POST methods.

PHP. How to find the previous page?

I would like to know what page redirected to the current page on my system.
For example. If the system stopped in the page current.php.
How to know what page called current.php?
Is there a function to perform this?
$_SERVER['HTTP_REFERER'] can contain the URL of the page the user agent was previously on, but it can be spoofed or empty.
You don't have a reliable way of doing that.
If you're expecting the redirecting page to be on your server, you can set a $_SESSION variable to the current page on every page you visit, that way, you can check for it on the next page (before resetting it of course).
Maybe there are better solutions, but you could use a hidden field inside a form to transfer this information between pages inside your system, or use GET vars in your URL.
Rhis way you can keep track of certain states during page changes, that u are interested in.
But u would also need to update every page to handle the additional variables.

HTTP_REFERER initiated HTML visible throughout website not just on the initial landing page

I have been looking for ever for a solution to my problem - I’m not a PHP newbie but am not overly experienced in it.
My problem is this:
I have a set of sites - one being the parent site. I want to have it so that if I hit any of my child sites from the parent site only, a back to parent button appears (wrapped in a div). If I hit any of the child sites directly or from another referrer then the button doesn't appear.
I have this working using HTTP_REFERER but I would like the button to remain visible when you click the through the site (obviously the referrer changes once I start clicking through the site).
This works for the button appearing on first hitting the site:
<?php if (preg_match("~^http://www.mysite.com~i", $_SERVER['HTTP_REFERER'])) { ?>
<div>Back</div>
<?php } ?>
But as I say I would like it to remain whilst I am navigating the site - I have looked at setting up a session but I can't get this to work either - the referrer always changes once I start navigating.
I appreciate this is a little vague but I have tried so many code samples and they all seem to have the same issues.
Any help would be much appreciated.
Thanks
Well the HTTP_REFERRER is indeed the last referer of the current page, so you have to store and start a session the first time you enter the site.
Sessions are usually a very simple subject that should work out of the box:
session_start();
session_regenerate_id();
if (preg_match("~^http://www.mysite.com~i", $_SERVER['HTTP_REFERER'])) {
$_SESSION['parentsite'] = true;
}
And later in your code do:
<?php if(isset($_SESSION['parentsite']) && $_SESSION['parentsite'] == true){ ?>
<div>Back</div>
<?php } ?>
Now if your sessions still don't work with that, it could be a COOKIE problem or a server configuration problem...
<?php
session_start();
if (!isset($_SESSION["ref"])){
$_SESSION["ref"] = $_SERVER["HTTP_REFERER"]; //record first instance
} else if (isset($_SERVER["HTTP_REFERER"])){
$ref = $_SERVER["HTTP_REFERER"];
if ($ref != $_SESSION["ref"]){
$_SESSION["ref"] = $ref; // record new ref
}
}
if ($ref = $_SESSION["ref"]){
echo "Back
}
BUT I agree with Pekka, that you should use custom site_id which is passed along whilst you navigate your site. Relaying on HTTP_REFERER is generally unsafe. And using session would run you into problem if you come to your master site from two child sites, as session would hold only latest ref.
In other solution of ours, we use get param "current_ref", which contains encoded referer url, created by the source site. This param is "sticky", and is passed all along the way, so at any point of time you can return to the originating site. Probably it would be better for you to implement such approach as well.
Edit: On closer look, a session based approach might be just enough for this specific situation, if there is only one parent site and multiple children, but no multiple parents! In a more complex situation however, sessions will send you to hell, so I'll leave this answer in place.
This is not trivial -
you could use sessions to store the referrer target across pages, but that would get confused if the user opens multiple instances of the same page from different referrers, which is horrible for usability
or send a unique key along with each request that points to the correct "back" target. (It could also be the base64 or URL encoded URL itself, but that would make the URLs look long and ugly...)
The latter is a very clean approach, but a pain to implement consistently.
One other (crazy and untested) idea that comes to mind is storing a base64 encoded representation of the referrer URL using JavaScript in the window.name property. The nice thing about that is that unlike a cookie, it stores the "back" target for the current window only. I can't guarantee this will work, but it might be worth following up on if you really want to do this.
As soon as I saw your question I thought that a SESSION would be the key.
You could set a session cookie and then test to see if the cookie already exists.
session_start();
if (preg_match("~^http://www.mysite.com~i", $_SERVER['HTTP_REFERER']) ||
isset($_SESSION['show_back_button']))
{
// Set the session value
$_SESSION['show_back_button'] = true;
echo '<div>Back</div>';
}

Go back to calling website

after searching (and testing) a way to offer a kind of go-back button I am asking that question here (maybe there is an easy solution).
I have a description about orienteering on my website (5 pages): http://www.uhebeisen.net/o-def/o-definition_ge.php
There are many websites from abroad having a link to this pages. Now I'd like to get their URL if a websurfer is entering my pages. Then I can place a button go-back to my navigation list that brings him back to his page from where he clicked the link to my description-pages.
I've seen solutions using javascript:history.go(-1) or $_SERVER['HTTP_REFERER'] with PHP but problem is that a websurfer can move around my pages and if finishing his reading from any page should be provided with his (calling) URL, e.g. the one of his University.
So I need to catch his URL and store it in a safe place until he decides to leave. And if he returns to the starting page while surfing on my pages his URL shouldn't be overwritten.
Since I do not program - just copy&paste and try to understand what happens. Any suggestion on how this can be done is welcome.
thank you George, that one worked
I wasn't aware to place the session_start at the very beginning of the file that's why I get the two warnings.
While testing this function I found that the session variables were not always cleared by the browser. Especially with Firefox, it keeps the calling URL almost forever (WinXP, FF 5.x) whereas Firefox 5 on the Mac, Safari (Mac) and Camino (Mac) work as expected: after restarting the program I can test successfully with another website.
Does Firefox have different setting possibilities in regard of sessions than other browsers?
You should store $_SERVER['HTTP_REFERER'] in the user's session upon arrival. Using this method, the value won't be overritten when the user browses within your site.
session_start();
if ( !isset( $_SESSION['referrer'] ) ) {
if ( !empty( $_SERVER['HTTP_REFERER'] ) ) { // Because not all browsers set this
$_SESSION['referrer'] = $_SERVER['HTTP_REFERER'];
}
}
One way to do it would be to store somewhere (perhaps in a cookie or session, which easy to do with your PHP page) the page they're coming from, but only if that page is not on your website's domain. This would require some if-statements to set the cookie/session value appropriately, but it can be done relatively easily using particular parts of the referrer variable. There is probably a more efficient way to store this, but this is one that jumps to mind right away.
EDIT: I highly recommend George's solution, much better way to do this.
Have you tried using a session?
session_start();
if( !isset($_SESSION['refer']) )
{
$_SESSION['refer'] = $_SERVER['HTTP_REFERER'];
}
then, once your ready to make the button, set the link to $_SESSION['refer'].
In my past projects I usually stores the redirect url following this process:
search for a query string parameter url (www.yoursite.com/?redirect_url=my_encoded_url)
If search at point 1 doesn't return any results, then I checks for the HTTP_REFERER
In both cases, I stores that value in a SESSION variable after verified that the url belongs to my site's domain.

Categories