Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- Template Name: Check HTTP Referrer
- Description: Page template with referrer tracking by hostname. Allowed hostnames are defined in a custom field named 'allowed-hosts'. Use full hostnames (e.g. www.facebook.com vs facebook.com) and separate multiple values with a space. The template works as a normal page template if there's no custom field set or if 'track-referrer' is not set.
- */
- // set vars
- // HTTP referrer
- $referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : false;
- // get array of allowed hosts from custom field
- $allowed_hosts = get_post_meta( $post->ID, 'allowed-hosts', true );
- $allowed_hosts = !empty($allowed_hosts) ? explode( ' ', $allowed_hosts ) : false;
- // custom field switch to turn tracking on/off
- $tracking = get_post_meta( $post->ID, 'track-referrer', true );
- $tracking = ($tracking == '1') ? true : false;
- // error message and status
- $error_msg = 'Not allowed.';
- // debug
- if(is_user_logged_in()) {
- $debug = '<pre>';
- $debug .= '<br />Enabled: ' . var_export($tracking, true);
- $debug .= '<br />Referrer: ' . var_export($referrer, true);
- $debug .= '<br />Host: ' . var_export(parse_url( $referrer, PHP_URL_HOST ), true);
- $debug .= '<br />Allowed hosts: ' . var_export($allowed_hosts, true);
- $debug .= '</pre>';
- $error_msg .= $debug;
- echo $debug;
- }
- // if referrer is set and custom fields exist
- if( $referrer && $allowed_hosts && $tracking ) {
- // get hostname from referrer
- $host = parse_url( $referrer, PHP_URL_HOST );
- // add current page to array of allowed hosts because of form validation/submission
- $allowed_hosts[] = parse_url(get_permalink(), PHP_URL_HOST);
- // compare referrer to array of allowed hosts
- if ( in_array ( $host, $allowed_hosts, true ) ) {
- // load page template
- locate_template( array('page.php'), true, true);
- // referrer is not allowed
- } else {
- // error message and status
- wp_die($error_msg, '', array( 'response' => 403 ) );
- }
- // no referrer but custom fields exist
- } elseif ( !$referrer && $allowed_hosts && $tracking ) {
- // error message and status
- wp_die($error_msg, '', array( 'response' => 403 ) );
- // no custom field (disable referrer tracking)
- } else {
- // load page template
- locate_template( array('page.php'), true, true);
- }
Advertisement
Add Comment
Please, Sign In to add comment