Page 1 of 1

cookies set in php, read in javascript

Posted: Mon Nov 02, 2009 2:22 am
by DrPL
Hi,
I'm a beginner with javascript and am a bit confused about how to access cookies.
I have set a cookie in php using setcookie("allow", "allow", time()+31536000, "paullee.com")
and I can see this in my cookie list in Firefox (tools->options), and the Name, content, expiry date etc. are all OK.

But when I try to access this cookie using javascript I get nothing. I got some code from the internet and it looks OK to me; I am putting this in the head section of my webpage.

Code: Select all

<script type="text/javascript">
<!--
 
    var x = readCookie('allow');
    if (x) 
    {
    window.location = "http://www.paullee.com/placeholder.html"
    }
 
 
    function readCookie(name) 
    {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) 
    {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
    }
 
//-->
</script>
Basically, I want any people who satisfy the "allow" cookie criteria to be forwarded
to another webpage. I really can't see what is wrong with the code.