PHP无法读取javascript cookie

问题描述:

I am setting a cookie with javascript and trying to read it with PHP, but php is not able to read it. I have checked that the cookie is really set with a tool called Cookies Manager.

Code(JS):

<script>
document.cookie="encrIv=" + ivB64;
</script>

Code(PHP):

<?php
$encrIv = $_COOKIE['encrIv'];
echo $encriv;
?>

I get

Notice: Undefined index: encrIv in C:\Users\joonas\Desktop\Webon cmsooteadCookie.php on line 1

Screen shot of cookie:

Cookies Manager screenshot

我正在设置一个带有javascript的cookie并尝试用PHP读取它,但是php无法读取它。 我已经检查过cookie是用一个名为Cookies Manager的工具设置的。 p>

Code(JS): p>

 &lt; script&gt;  
document.cookie =“encrIv =”+ ivB64; 
&lt; / script&gt; 
  code>  pre> 
 
 

代码(PHP): p>

 &lt;?php 
 $ encrIv = $ _COOKIE ['encrIv']; 
echo $ encriv; 
?&gt; 
  code>  pre> 
 
 

我得到 p>

注意 strong>:未定义的索引: C:\ Users \ joonas \ Desktop \ Webon cms oot eadCookie.php中的encrIv strong>在线 1 strong> strong> blockquote>

Cookie的屏幕截图: p>

p> div>

<!DOCTYPE html>
<html>
  <head>
    <title>example</title>
    <script type="text/javascript">
       document.cookie = 'name=David' ;
    </script>
   </head>
   <body>
    <?php
       var_dump($_COOKIE['name']);
    ?>
   </body>
 </html>

with this the cookie is set. Did you correct your Typo? You wrote:

<?php
$encrIv = $_COOKIE['encrIv'];
echo $encriv;
?>

the correct way is to change the echo to

echo $encrIv;

or to change your variable to

$encriv = $_COOKIE['encrIv'];

EDIT:

Maybe your Problem is the not defined Path. define a cookie like this:

document.cookie = 'sconName='+changedName+'; path=/'

change your code specially the echo part from $encriv to $encrIv like this simple example

say this is index.php which you need to visit first.The file that will set a value of encrIv cookie

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript">
        document.cookie="encrIv=samplecookie";
    </script>
</head>
<body>
    <?php 

        $encrIv = isset($_COOKIE['encrIv'])?$_COOKIE['encrIv']:'';
        echo $encrIv;
    ?>
</body>
</html>

then this your readCookie.php which you will visit after index.php has been loaded.

 <?php 

            $encrIv = isset($_COOKIE['encrIv'])?$_COOKIE['encrIv']:'';
            echo $encrIv;
        ?>

That should clearly help you myfriend

Your code works fine for me, if I refresh the page after it has been loaded.

Your javascript code will be run after the php code (when the php interpreter has processed the html+php code and the browser interprets the processed html code), which means that when you try to access it using php it is not set yet. But when you reload the page the cookie will be there and php can access it.