Place a cookie when a specific page has been viewed?

I’ve worked out a solution. There may be a more elegant way to achieve this, but I had trouble getting anything else to work.

I’ve placed the following code at the beginning of the header.php file for all pages. The objective is to funnel site visitors through an event registration page, prior to accessing the site’s content:

$currentURL = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

if ( $currentURL == 'http://mydomain.com/website-registration/' ) :

elseif ( $currentURL != 'http://mydomain.com/thank-you/' ) :

    if ( ! isset( $_COOKIE["tcpa_newvisitor"] ) ) :
        header( "Location: http://mydomain.com/website-registration/" );
    endif;

else :

    if ( ! isset( $_COOKIE['tcpa_newvisitor'] ) ) :
        setcookie( 'tcpa_newvisitor', 1, time() + 3600 * 24 * 100, COOKIEPATH, COOKIE_DOMAIN, false);
        header( "refresh:1;url=http://mydomain.com" );
    endif;

endif;

The code collects the current page in $currentURL. If the current page is the target website registration page, then nothing happens. If the URI is anything other than the thank you page, and the cookie has not yet been set, the browser redirects to the registration page. When the form on the registration page has been submitted, the user is directed to the thank you page where the cookie is set. Finally, after 1 second, the thank you page refreshes, redirecting to the home page. The visitor can now view the site as normal.

Leave a Comment