Search code examples
phpwordpresshttp-refererreferer

How to put a redirect in front of a php template with a referer check?


I have a template in my (wordpress) child theme folder for a custom post type that I created. It looks like this:

<head>
    …
    <style>
        …
    </style>
    <script>
        …
    </script>
</head>

<header>
    …
</header>

<?php
    …
?>

<div id="content">
    <?php xx_page_header($post->ID); ?>
    …
</div>

<?php get_footer(); ?>

This is exactly how it is structured. I put it because I am php beginner and if someone is willing to help me, at all, I will most of all need exact information where exactly to put code snippets (which in the end will look simple and small, I guess).

I have 4 pages that are based on this template page. All of them working well.

Here is what I have to add though:

The pages succeed each other containing input forms etc. and are clicked through by passing the forms, sort of a filtering process.

How can I put in front of the template a referer check? So that the pages keep on working their way BUT if someone would copy one of the links and paste it into another browser window he would be redirected always to the first page of them instead of seeing the page of the actual link.

I have made some researches as good as I can and found some pieces I would like to use. As is for:

1) the referer part:

<?php
    $ref=getenv("HTTP_REFERER");
    $url='url_redirect';
    if($ref!='referer_url'){
       header('Location: '.$url);
    }
?>

2) a regex to make it work for all pages that are using the template:

ref.match(/^http?:\/\/([^\/]+\.)?mywebpage\.com(\/|$)/i)

Let’s say the (filtering) start page is: www.mywebpage.com/startpage/

How do I have to combine those snippets and where to put it (I guess at the beginning of the template)?

I would like to avoid cookies. (using the referer)


Solution

  • Technically, you could do something similar to the code below. Each of your pages after the start page must have unique urls and a token that is passed along on every page. You need to place this code at the very top of your template.

    Something similar:

    <?php    
        $url='url_redirect';
        if((is_page('template2') || is_page('template3') || is_page('template4')) && $_POST['token'] == '') {
           header('Location: '.$url);
        }
    ?>