Snapcaster
Snapcaster

Reputation: 159

Strings not working in my cookies

I need to make some cookies in the middle of my document, but I hear you cannot make a cookie with PHP after outputting anything.. So I decided to output my variables to javascript to set the cookie. The setCookie function is included earlier in the code. The problem is that the cookies are not being set. If I pass numeric values in for click_id or SID, the cookies are set, but if I pass letters in, the cookies are not set.

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

<?php echo '<script>setCookie("click_id",'.$_GET["click_id"].',30);setCookie("SID",'.$_GET["SID"].',30);</script>'; ?>

Thanks in advance

Upvotes: 1

Views: 70

Answers (1)

Kai Qing
Kai Qing

Reputation: 18843

Have you tried passing them as strings? By that I mean double quoting the values. Currently you are not quoting, so it will try to evaluate as int.

<?php echo '<script>setCookie("click_id","'.$_GET["click_id"].'",30);setCookie("SID","'.$_GET["SID"].'",30);</script>'; ?>

An alternative and much easier read would be:

<script>
    setCookie("click_id","<?php echo $_GET["click_id"]; ?>",30);
    setCookie("SID","<?php echo $_GET["SID"]; ?>",30);
</script>

Upvotes: 2

Related Questions