在 Cookie 中使用保存的变量与 PHP 一起使用


use saved variable in cookie with php

在过去的两周里,我一直在努力将页面ID保存在cookie中,然后在其他页面中检索它。

最后我解决了它,但现在我还有其他一些问题,我想在我的 php 代码中使用此 id(我保存在 cookie 中并检索它的那个)。

我知道javascript是客户端代码,php是服务器端代码,但我必须这样做。请帮我解决这个问题。

这是我的javascript代码,它运行良好,我得到了保存的id,并带有此行"+ value.favoriteid+"

<script>
   /*
  * Create cookie with name and value.
  * In your case the value will be a json array.
  */
  function createCookie(name, value, days) {
    var expires = '',
    date = new Date();
    if (days) {
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      expires = '; expires=' + date.toGMTString();
    }
    document.cookie = name + '=' + value + expires + '; path=/';
  }
  /*
  * Read cookie by name.
  * In your case the return value will be a json array with list of pages saved.
  */
  function readCookie(name) {
    var nameEQ = name + '=',
    allCookies = document.cookie.split(';'),
    i,
    cookie;
    for (i = 0; i < allCookies.length; i += 1) {
      cookie = allCookies[i];
      while (cookie.charAt(0) === ' ') {
        cookie = cookie.substring(1, cookie.length);
      }
      if (cookie.indexOf(nameEQ) === 0) {
        return cookie.substring(nameEQ.length, cookie.length);
      }
    }
    return null;
  }
  function eraseCookie(name) {
    createCookie(name,"",-1);
}
    var faves = new Array();
$(function(){
    var favID;
    var query = window.location.search.substring(1);
	var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        var favID = (pair[0]=='ID' ? pair[1] :1)
//alert(favID);
	}
	$(document.body).on('click','#addTofav',function(){
    var fav = {'favoriteid':favID};
    faves.push(fav);
	var stringified = JSON.stringify(faves);
    createCookie('favespages', stringified);
    location.reload();
	});
  var myfaves = JSON.parse(readCookie('favespages'));
    if(myfaves){
    faves = myfaves;
    } else {
    faves = new Array();
    }
    $.each(myfaves,function(index,value){
      var element = '<li class="'+index+'"><h4>'+value.favoriteid+'</h4>   ';
      $('#appendfavs').append(element);
    });
});
 </script>

阅读 cookie 在php面上,通过js设置它们后,这是最简单的事情。

从客户端发送给您的任何 cookie 将自动包含在内 如果variables_order包含"C",则转换为 $_COOKIE 的自动全局数组。如果 您希望为单个 cookie 分配多个值,只需将 [] 添加到 饼干名称。 根据register_globals,可以创建常规的PHP变量 从饼干

以下是一些例子:

<?php 
echo $_COOKIE["your cookie name"];
?>
<?php
print_r($_COOKIE);
?>

不建议依赖它们,因为这样 为了安全起见,功能经常被关闭。

http://php.net/manual/en/features.cookies.php

如果您已经设法在 javascript 中保存到 cookie,那么在 PHP 中检索它应该没有问题,只需使用 $_COOKIE["COKKIE_NAME"](您当然可以更改COOKIE_NAME,更改为您在 JS 中保存的 cookie 的名称)。

查看 http://php.net/manual/en/features.cookies.php 以获取更多示例。