Use PHP to ensure a page can only be accessed via a specific URL
Use this handy PHP script to redirect visitors who access a web page via an external link or by typing the URL directly into their browser.
A situation recently arose where I wanted to redirect all traffic that accessed a certain URL (either directly or via an external site) unless that traffic arrived via a hyperlink on my website.
The following PHP script will perform the following functions:
- Check the HTTP referrer to see whether the visitor has come from a page on an approved website (host)
- If the visitor has come from an approved website, display the page content
- If the referrer page is unapproved, redirect to another defined page
- If a direct call is made for the page, redirect to another defined page as if the page was accessed from an external link.
This simple script is ideal for ‘presentation’ purposes but should not be used where security is an important concern as referrer data can be spoofed.
The following code should be added at the very top of a PHP file, even before the <!DOCTYPE>:
<?php
$referer = $_SERVER['HTTP_REFERER'];
$referer_parse = parse_url($referer);
if($referer_parse['host'] == "example.com" || $referer_parse['host'] == "www.example.com") {
// Page content will display
} else {
header("Location: http://www.example.com/redirected-page");
exit();
}
?>
You will need to replace “example.com” and “www.example.com” with your website (assuming you only want to permit links from your own website). Otherwise add the hostnames of websites from which you will accept referrer traffic.
You will then need to replace “http://www.example.com/redirected-page” with the URL of a page that you wish to redirect people to if they enter the page’s URL directly, or access the page from an ‘unapproved’ link.
Now, if people try to access the page directly or via an external link, they will instantly be redirected to another page.
Comments
3 responses to “Use PHP to ensure a page can only be accessed via a specific URL”
Thanks Adam, I was looking for some PHP redirect code to allow only internal links to access a wholesale pricing page on an eCommerce website and this was the code I was looking for!
I don’t see the php code here, where can I find it?
Sorry Steve, there was a rendering problem that I’d not identified from the website upgrade. All is fixed now and you should be able to see the code.