如何在Wordpress中设置会话和Cookie中的动态变量

时间:2016-10-03 12:51:33

标签: php wordpress

我正在尝试存储来自外部链接?dynamic=a_12_bc的动态变量,并将链接显示为此http://www.myweb.com?tracker=a_12_bc 第一次它总是显示动态链接,但是当我刷新并点击其他页面时,它会显示?tracker=[object][Object]

<?php session_start(); 
 echo $_GET['dynamic'];
if( isset($_GET['dynamic']))
{
  $cookie_name = "dynamic";
  $cookie_value = $_GET['dynamic'];
  setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
  $_SESSION["dynamic"] = $cookie_value;
  }
else
{   
 $_SESSION["dynamic"] = $_COOKIE['dynamic'];
 }?>
 Button Link
<a href="https://www.myweb.com/?tracker=<?php echo($_SESSION['dynamic']);?>" target="_blank">LOG IN</button></a>

您能否告诉我如何在其他页面上维持会话

1 个答案:

答案 0 :(得分:1)

检查cookie是否已设置,然后在代码中添加isset()将其分配给会话。

if(isset($_GET['dynamic']))
{
   $cookie_name = "dynamic";
   $cookie_value = $_GET['dynamic'];
   setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
   $_SESSION["dynamic"] = $cookie_value;
}
else if(isset($_COOKIE['dynamic'])) {
   $_SESSION["dynamic"] = $_COOKIE['dynamic'];
}
else
{
   //something here
}

如果未设置cookie,请尝试在setcookie()方法中添加域,

setcookie( $cookie_name , $cookie_value , time() + (86400 * 30), '/', COOKIE_DOMAIN );

如果您需要更多信息,请参阅此链接https://premium.wpmudev.org/blog/set-get-delete-cookies