简体   繁体   中英

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. The goal is to move the JavaScript variable ( test ) to the PHP variable ( $_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. 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?

Let's understand how your code works:

  1. Browser request the page yourpage.php. For the first run the cookie is empty, so on the server side your cookie is empty anycase.

  2. Browser loads the page with your JS, actually for the first run it is equals:

     <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

  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.
  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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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