$_SERVER['HTTP_REFERER'] - how to make if to compare with base url

3.5k views Asked by At

I'm trying to compare value of HTTP_REFERER and my base url . How to do that? If I write it in this way, it doesn't show back button. If I use whole url of my project: http://localhost/myproject/index.php/home/index It works, but I want to compare base url - not to write many if conditions for each page. How could I do that?

<?php 
if ((isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) )) {
    if ($_SERVER['HTTP_REFERER'] ==  'http://localhost:/myproject/') {
        echo '<a type="button" onclick="history.back(-1);">Back</a>';
    }
}

Edited: In this way it'working but it's showing this warning: Message: strtolower() expects parameter 1 to be string, array given How to fix it?

<?php
if ((isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) )) { $referer = $_SERVER['HTTP_REFERER']; $current = 'localhost:/myproject/';
$ref =parse_url($referer); $my=parse_url($current);
if (strtolower($ref) === strtolower($my)) { echo '<a type="button" onclick="history.back(-1);">Back</a>'; } }

3

There are 3 answers

1
Adam On BEST ANSWER

check if in HTTP_REFERER its constains your domain.

if (isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], 'localhost/myproject' !== false))
{
  echo '<a type="button" onclick="history.back(-1);">Back</a>';
} 
3
RuubW On

Try the following:

if ((isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) )) {
    $referer = $_SERVER['HTTP_REFERER'];
    $current = 'http://localhost:/myproject/'; // Do you mean for the : to be here?

    $refererBaseUrl = trim(preg_replace('/\?.*/', '', $referer), '/');
    $currentBaseUrl = trim(preg_replace('/\?.*/', '', $current), '/');

    if (strtolower($refererBaseUrl) === strtolower($currentBaseUrl)) {
        echo '<a type="button" onclick="history.back(-1);">Back</a>';
    }
}

This is the basic technique that I use to compare base URLs.

Edit:

How about using parse_url (http://php.net/manual/en/function.parse-url.php) to parse both URLs and compare results?

0
Oliver Hemsted On

You can get the base URL using $_SERVER['HTTP_HOST'] you may need to append http/https to the string.

You can also then use $_SERVER['REQUEST_URI'] to get the remainder of the URL.