duancan5327 2016-07-06 14:15
浏览 35

会话变量未保留在wordpress中

I have written an API in php that is called by a script running with google tag manager.

The use for the script is to supply each visitor with a unique telephone number on the site

During testing i managed the user tracking by adding a cookie with the php session ID. This allowed me to query the database to see if they where already assigned a number and if they whernt then i need to assign one.

In testing this worked perfectly, however when implementing within a wordpress platform the cookies are not set .Therefore every time the script is called (on page change) i receive a new number.

Method 1 Set cookie on client and retrieve using $_Cookie['MyCookie']

Method 2 Create a session and check for a session id ever time the script is called. Session ID is changing every time...failed

Method 3 Attempt to use the ga visitor id(cid) to track the user, this also generates a different number every time

I have tried a number of solutions to resolve this but currently i cant stop the behievour.

Script is currently configured to use the GA CID and looks like this

<?php
header("Access-Control-Allow-Origin: *");

error_reporting(-1);
ini_set('display_errors', 'On');

$servername = "";
$username = "";
$password = "";
$dbname = "";

$cookie_name = "TestCookie";
$numID;

$site_id = "";
$domain_name = $_POST['url'];


if(isset($domain_name)) {
            $conn_siteID = new mysqli($servername, $username, $password, $dbname);

            $sql_siteID = "Select * from SiteList where ReferrerURL = '" . $domain_name . "'";

            $result = $conn_siteID->query($sql_siteID);

            if ($conn_siteID->connect_error) {
                die("Connection failed: " . $conn_siteID->connect_error);
            }           

            if ($result->num_rows > 0) {
                while($row = $result->fetch_assoc()) {
                    $site_id = $row["id"];
                }
            } else {

            }
            $conn_siteID->close();
}

$cid = gaParseCookie();
echo $cid;

if(!empty($cid)) {
            //Cookie doesnt exist give them a new number

            $conn = new mysqli($servername, $username, $password, $dbname);
            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);
            } 


            $sql = "Select * from NumPool where cid='". $cid . "' order by lastshown asc limit 1";
            $result = $conn->query($sql);

            if ($result->num_rows > 0) {
                while($row = $result->fetch_assoc()) {
                    //return current number
                    echo $row["number"];
                    $numID = $row["id"];

                    $conn4 = new mysqli($servername, $username, $password, $dbname);
                    $sql = "Update NumPool set lastshown='" . date("Y-m-d H:i:s") . "', cid='". $cid ."' where id='" . $numID . "'";
                    $result = $conn4->query($sql);
                    $conn4->close();
                }
            } else {
                //return new number
                    $conn3 = new mysqli($servername, $username, $password, $dbname);

                    if ($conn3->connect_error) {
                        die("Connection failed: " . $conn3->connect_error);
                    } 

                    $sql = "Select * from NumPool where siteid='". $site_id . "' order by lastshown asc limit 1";
                    $result = $conn3->query($sql);

                    if ($result->num_rows > 0) {
                        while($row = $result->fetch_assoc()) {
                            echo $row["number"];
                            $numID = $row["id"];

                            $conn4 = new mysqli($servername, $username, $password, $dbname);
                            $sql = "Update NumPool set lastshown='" . date("Y-m-d H:i:s") . "', cid='". $cid ."' where id='" . $numID . "'";
                            $result = $conn4->query($sql);
                            $conn4->close();
                        }
                    } else {

                    }

                    $conn3->close();

            }
            $conn->close();

} 


// Handle the parsing of the _ga cookie or setting it to a unique identifier

function gaParseCookie() {
  if (isset($_COOKIE['_ga'])) {
    list($version,$domainDepth, $cid1, $cid2) = preg_split('[\.]', $_COOKIE["_ga"],4);
    $contents = array('version' => $version, 'domainDepth' => $domainDepth, 'cid' => $cid1.'.'.$cid2);
    $cid = $contents['cid'];
  }
  else $cid = gaGenUUID();

  return $cid;
}

// Generate UUID v4 function - needed to generate a CID when one isn't available
function gaGenUUID() {
  return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
    // 32 bits for "time_low"
    mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),

    // 16 bits for "time_mid"
    mt_rand( 0, 0xffff ),

    // 16 bits for "time_hi_and_version",
    // four most significant bits holds version number 4
    mt_rand( 0, 0x0fff ) | 0x4000,

    // 16 bits, 8 bits for "clk_seq_hi_res",

    // 8 bits for "clk_seq_low",
    // two most significant bits holds zero and one for variant DCE1.1
    mt_rand( 0, 0x3fff ) | 0x8000,

    // 48 bits for "node"
    mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
  );
}
?>
  • 写回答

1条回答 默认 最新

  • douxian1895 2016-07-11 10:06
    关注

    I was unable to resolve the above via a server side php implementation. I have opted to inject a script on page load to perform the actions client side

    tracking code implemented in GTM

    <script type="text/javascript">
        (function () {
        var ra = document.createElement('script');
        ra.type = 'text/javascript';
        ra.src = ('https:'==document.location.protocol?'https://':'http://')
        +'www.test.co.uk/app/getcd.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(ra, s);
        }());
    </script>
    

    Script implementation

    var cookieName = "";
    var cookieValue = getCookie(cookieName);
    var accountId = getAccount();
    
    
    if (cookieValue == "") {
        cookieValue = guid();
        setCookie(cookieName, cookieValue, 30);
    }
    
    // request number using cookieValue
    var url = "etcd.php";
    var params = "url=" + document.domain + "&userid=" + cookieValue + "&gaAccountID='" + accountId;
    
    
      if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
      } else {  // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    
        var numberfields = document.querySelectorAll('.complete');
        for(var i = 0; i < numberfields.length; i++) {
            if (xmlhttp.responseText !== "") {
                numberfields[i].innerHTML=xmlhttp.responseText;
            }
    }
    
        }
      }
      xmlhttp.open("POST",url,true);
      xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xmlhttp.send(params);
    
    
    
    
    
    function setCookie(cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays*24*60*60*1000));
        var expires = "expires="+d.toUTCString();
        document.cookie = cname + "=" + cvalue + "; " + expires;
    }
    
    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }
    
    function guid() {
      function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
          .toString(16)
          .substring(1);
      }
      return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
        s4() + '-' + s4() + s4() + s4();
    }
    
    评论

报告相同问题?