PHP cannot read javascript cookies

六月ゝ 毕业季﹏ 提交于 2020-01-05 03:59:08

问题


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 cms\root\readCookie.php on line 1

Screen shot of cookie:


回答1:


<!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=/'



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/31672232/php-cannot-read-javascript-cookies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!