Simply store it in the session and always check for if its set:
$_SESSION['ref'] = getenv('HTTP_REFERER'); // or $_SERVER['HTTP_REFERER'] would work
// Do your checks here.
So long as that's included in any page that needs to check, it should carry that over.
The only thing to note is that there is no guarantee that HTTP_REFERER will ever be available. That's completely up to the client if they want to provide that to you or not.