简体   繁体   English

PHP / JavaScript cookie的行为就像一个指针,因此当我清除它时,我会失去价值; 如何从Cookie中获取价值?

[英]PHP/JavaScript cookie acting like a pointer so when I clear it, I lose the value; how do I grab the value from the cookie?

<script type="text/javascript">
    var test = "test";
    document.cookie = "some_test=" + guid;
</script>

<?php $_POST['important_value'] = ((isset($_COOKIE['some_test'])) ? ($_COOKIE['some_test']) : ('')); ?>

<script>
    //document.cookie = "some_test=;expires=Thu, 01 Jan 1970 00:00:00 UTC;";
    console.log(document.cookie);
</script>

This code works exactly as intended so long as I don't uncomment the line to clear the cookie. 只要我不取消注释清除cookie的行,此代码就可以按预期工作。 The goal is to move the JavaScript variable ( test ) to the PHP variable ( $_POST['important_value'] ). 目标是将JavaScript变量( test )移到PHP变量( $ _POST ['important_value'] )。

I think what's happening is that $_POST['important_value'] and $_COOKIE['some_test'] are pointing to the same thing but I could be wrong. 我认为正在发生的事情是$ _POST ['important_value']$ _COOKIE ['some_test']指向同一件事,但我可能是错的。 Is there anyway to print the address of the variables? 反正有打印变量的地址吗?

UPDATE: 更新:

debug_zval_dump($_POST['important_value']);
// string(39) "750118664537365903071115537365768136624" refcount(3)

debug_zval_dump($_COOKIE['some_test']);
// string(39) "750118664537365903071115537365768136624" refcount(3) 

I'm assuming this means my assumption is correct? 我假设这意味着我的假设是正确的? How do I get the string value from the cookie without the pointer? 我如何从没有指针的cookie中获取字符串值?

Let's understand how your code works: 让我们了解您的代码如何工作:

  1. Browser request the page yourpage.php. 浏览器请求页面yourpage.php。 For the first run the cookie is empty, so on the server side your cookie is empty anycase. 第一次运行时,cookie为空,因此在服务器端,cookie始终为空。

  2. Browser loads the page with your JS, actually for the first run it is equals: 浏览器使用您的JS加载页面,实际上第一次运行就等于:

     <script type="text/javascript"> var test = "test"; document.cookie = "some_test=" + guid; </script> <script> //document.cookie = "some_test=;expires=Thu, 01 Jan 1970 00:00:00 UTC;"; console.log(document.cookie); </script> 
  3. Browser receiving the cookie from your JS 浏览器从您的JS接收cookie

  4. On the next visit your PHP code sees the cookie and you assign it to the POST variable, which finishes it's life after the page execution. 在下一次访问时,您的PHP代码将看到cookie,然后将其分配给POST变量,从而完成了页面执行后的生命。
  5. If you destroy the cookie (by uncomment your commented line), at 3rd step browser removes the cookie, so on 4th stage browser doesn't see your cookie :) 如果您破坏了cookie(通过取消注释注释行),则在第3步浏览器将删除cookie,因此在第4阶段浏览器将看不到您的cookie :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM