PHP vs Javascript cookie diff?

General discussions related to php

Moderators: egami, macek, gesf

Post Reply
penguinjeff
New php-forum User
New php-forum User
Posts: 1
Joined: Thu Dec 21, 2017 10:55 am

Thu Dec 21, 2017 11:05 am

I have 2 pages
test_cookie.html

Code: Select all

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script>
function listCookies() {
    var theCookies = document.cookie.split(';');
    var aString = '';
    for (var i = 1 ; i <= theCookies.length; i++) {
        aString += i + ' ' + theCookies[i-1] + "\n";
    }
    return aString;
}

function normalize(str)
{var pos=-1
 if((pos=str.search(/%[0-9a-f][0-9a-f]/))!=-1)
 {var before=str.substr(0,pos);
  var after=str.substr((pos+3));
  var now=String.fromCharCode(parseInt(str.substr((pos+1),2), 16));
  return normalize(before+now+after);
 }
 else
 {return str;
}}

function set_cookie()
{alert("retrieving cookie from test_cookie.php")
 var xmlhttp = new XMLHttpRequest();
 var url = "test_cookie.php?timestamp="+Date.now();
 xmlhttp.onreadystatechange = function()
 {if(this.readyState == 4 && this.status == 200)
  {
alert(document.cookie);
alert(listCookies());
alert(normalize(document.cookie));
  }
 };
 xmlhttp.open("GET", url, true);
 xmlhttp.send();
}
</script>
</head>
<body onload="set_cookie()">
<p>Testing cookie</p>
</body>
</html>
and
test_cookie.php

Code: Select all

<?php

if (isset($_SERVER['HTTP_COOKIE'])) {
    $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
    foreach($cookies as $cookie) {
        $parts = explode('=', $cookie);
        $name = trim($parts[0]);
        setcookie($name, '', time()-1000);
        setcookie($name, '', time()-1000, '/');
    }
}

function cc($s)
{$r='';
 foreach(str_split($s) as $c)
 {if(preg_match("/[a-z0-9!#$&'*+-.^_`|~]/i",$c))
  {$r.=$c;
  }
  else
  {$p='';
   if(ord($c)<16){$p='0';}
   $r.='%'.$p.dechex(ord($c));
 }}
 return $r;
}
setcookie('s',cc("test:0\n"));

//if(isset($_COOKIE['s'])){
echo $_COOKIE['s']."\n<br>";
//}else{echo "didn't create the cookie.\n<br>";}

?>
I am getting un expected results.

I have offset indexing in my javascript that accounts for the extra characters but where are the extra characters coming from?

if I go to test_cookie.php in a web browser I get

Code: Select all

test%3a0%0a 
after I visit it the second time. Why doesn't this work the first time the cookie seems empty.

If I go to test_cookie.html in a web browser the alerts show

Code: Select all

s=test%253a0%250a

Code: Select all

1 s=test%253a0%250a

Code: Select all

s=test:0
where does the 25 before my hex come from?

Post Reply