Reputation: 1289
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:
Upvotes: 2
Views: 2845
Reputation: 1813
<!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=/'
Upvotes: 3
Reputation: 3161
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
Upvotes: 1
Reputation: 819
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.
Upvotes: 1