会话变量未保留在wordpress中

时间:2016-07-06 14:15:52

标签: php wordpress session cookies

我在php中编写了一个API,该脚本由运行谷歌标记管理器的脚本调用。

该脚本的用途是为每位访客提供网站上唯一的电话号码

在测试期间,我通过添加带有php会话ID的cookie来管理用户跟踪。这使我能够查询数据库以查看它们是否已经分配了一个数字,如果它们是,那么我需要分配一个。

在测试中,这完美无缺,但是当在wordpress平台中实现时,cookie没有设置。因此,每次调用脚本时(在页面更改时),我都会收到一个新号码。

方法1 在客户端设置cookie并使用$ _Cookie检索[' MyCookie']

方法2 创建会话并在调用脚本时检查会话ID。会话ID每次都在变化......失败

方法3 尝试使用ga访客ID(cid)来跟踪用户,这也会每次生成不同的号码

我已经尝试了许多解决方案来解决这个问题,但目前我无法阻止这个问题。

脚本当前配置为使用GA CID,看起来像这样

<?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 个答案:

答案 0 :(得分:0)

我无法通过服务器端php实现解决上述问题。我选择在页面加载时注入一个脚本来执行客户端的操作

跟踪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>

脚本实现

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();
}