Marco Marco - 2 months ago 8
PHP Question

Need to know if a person comes to my website from a link inside my website, not an external website

I need to know if a person comes to my website from a link inside my website, not an external website. To be more precise, the links need to resemble something like

http://localhost/library/cat/5/fashion
http://www.mywebpage.com/library/cat/4/design

http://localhost/library/publication/7/pronto
http://www.mywebpage.com/library/publication/7/pronto


How do i find out if the HTTP_REFERER contains at least 'library/cat' or 'library/publication', and it's an internal link (comes from my live host, or localhost)?

Here's what i did so far

if ( isset($_SERVER['HTTP_REFERER') ) {

//if the referer contains something that resembles the above url's, add icon to go back

}

Answer

Actually your aproach is ok, but bear in mined that TRASTING ANY EXTERNAL DATA is not reliable and prone to hacks.

Using HTTP_REFERER, this is what I would do:

if ( !empty($_SERVER['HTTP_REFERER']) && strpos(strtolower($_SERVER['HTTP_REFERER']), '/library/cat/' ) !== false ) {

//if the referer contains something that resembles the above url's, add icon to go back

}

But if you really want to give the users a "Go Back" button, you have better solutions:

Use simple history(-1) in JS, thou this can send the user back to the search engine he came from:

function goBack() {
    window.history.go(-1);
}
<button onclick="goBack()">Go Back</button>

Your second option will be to relly on Cookies, this is a little bit more complicated but will give you the main idea

if (empty($_SESSION['current_page'])){
    // This is our first page in this website!
    $_SESSION['current_page'] = $_SERVER['REQUEST_URI'];
} else {
    // This is our second+ page in this website, we have a back button
    $_SESSION['prev_page'] = $_SESSION['current_page'];
    $_SESSION['current_page'] = $_SERVER['REQUEST_URI'];
}

Now with this example you can play with, you can make it as an array to have more the one History event and etc.

Comments