<?php
function _bot_detected() {
  return (
        isset($_SERVER['HTTP_USER_AGENT'])
        && preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT'])
  );
}

$mysqli = new mysqli('localhost', 'dfc_www', '7ucBa7sjYUaR', 'visits');

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$cookie_name = "AdsCustomerCode";	
if( !isset($_COOKIE[$cookie_name]) && !_bot_detected() ) 
{
    $domain = $mysqli->real_escape_string($_GET['domain']);
    $code = $mysqli->real_escape_string($_GET['code']);
    
    $query = "SELECT * FROM ad_tracking a WHERE a.`domain` = '".$domain."' AND a.`code` = '".$code."' LIMIT 1";

    if ($result = $mysqli->query($query)) {
        $visit = $result->fetch_assoc();
        
        if (isset($visit['id']) && !empty($visit['id'])) {
            setcookie($cookie_name, $code, time() + (86400 * 30 * 3), '/', 'sextortion.co.uk');
        }

        /* free result set */
        $result->free();
    }
}
