Browser Cookies with PHP and JavaScript

I have a game that I am in the process of updating. Originally it passed scores in with the URL, but I decided to update it so that the scores are not visible. My first thought was to use session variables, but since I want to change the scores in response to calculations that are done in JavaScript, that isn’t feasible. A better way is to use cookies. When I first enter a page, I set or get the cookies with PHP. I want the game levels to persist from visit to visit but the scores are only kept for the session.


// Initialize the cookies with PHP. Keep the group and level around but make the scoring session cookies
// If the cookie is set by the code, it is not available until the next page load
$cookie_name = "VPA_group";
$cookie_value = "MW1";
if( !isset($_COOKIE[$cookie_name]) ) {
    setcookie($cookie_name,$cookie_value,$cookie_time,$cookie_path,$cookie_domain,$cookie_secure,$cookie_httponly);
}
$group  = isset($_COOKIE["VPA_group"])  ? $_COOKIE["VPA_group"]   : $cookie_value;

$cookie_name = "VPA_WFF";
$cookie_value = "Wide";
if( !isset($_COOKIE[$cookie_name]) ) {
    setcookie($cookie_name,$cookie_value,$cookie_time,$cookie_path,$cookie_domain,$cookie_secure,$cookie_httponly);
}
$WFF    = isset($_COOKIE["VPA_WFF"])    ? $_COOKIE["VPA_WFF"]     : $cookie_value;

$cookie_name = "VPA_cor";
$cookie_value = 0;
if( !isset($_COOKIE[$cookie_name]) ) {
    setcookie($cookie_name,$cookie_value);
}
$cor    = isset($_COOKIE["VPA_cor"])    ? $_COOKIE["VPA_cor"]     : $cookie_value;

$cookie_name = "VPA_inc";
$cookie_value = 0;
if( !isset($_COOKIE[$cookie_name]) ) {
    setcookie($cookie_name,$cookie_value);
}
$inc    = isset($_COOKIE["VPA_inc"])    ? $_COOKIE["VPA_inc"]     : $cookie_value;

$cookie_name = "VPA_screen";
$cookie_value = 0;
if( !isset($_COOKIE[$cookie_name]) ) {
 setcookie($cookie_name,$cookie_value);
}
$screen = isset($_COOKIE["VPA_screen"]) ? $_COOKIE["VPA_screen"]  : $cookie_value;

Once I have the values, I need to let JavaScript know what they are.


<script>
    <?php
        echo "var cor = $cor;\n";
        echo "var inc = $inc;\n";
        echo "var screen = $screen;\n";

        echo "var group = \"$group\";\n";
        echo "var WFF = \"$WFF\";\n";
        echo "var cookie_days = \"$cookie_days\";\n";
    ?>
</script>

Then I can use JavaScript to change them, as I described in the previous post.


function goNext() {
    setCookie('VPA_cor',cor,'N');
    setCookie('VPA_inc',inc,'N');
    setCookie('VPA_screen',screen,'N');
    window.location="ThisGame.php";
}

function changeLevel(cookieName, cookieValue) {
    cor = 0;
    inc = 0;
    screen = 0;
    setCookie('VPA_cor',cor,'N');
    setCookie('VPA_inc',inc,'N');
    setCookie('VPA_screen',screen,'N');
    setCookie(cookieName, cookieValue, 'Y');
}

function setCookie(cname, cvalue, set_time) {
    var expires = '';
    if ( set_time == 'Y' ) {
        var d = new Date();
        d.setTime(d.getTime() + (cookie_days*24*60*60*1000));
        expires = "expires="+d.toUTCString();
    }
    //alert('cname ' + cname + 'group ' + cvalue + 'time ' + expires);
    document.cookie = cname + "=" + cvalue + "; " + expires;
}
</script>

Browser Cookies with JavaScript

Using JavaScript to set and get cookies is pretty straightforward. I wrote a simple function to set cookies for a game I’m working on. This code initializes/resets the cookies.


var cookie_days = 30;
var cor = 0;
var inc = 0;
var screen = 0;
var level = "MW1";
setCookie('VPA_cor',cor,'N');
setCookie('VPA_inc',inc,'N');
setCookie('VPA_screen',screen,'N');
setCookie('VPA_level',level,'Y');

function setCookie(cname, cvalue, set_time) {
var expires = '';
if ( set_time == 'Y' ) {
    var d = new Date();
    d.setTime(d.getTime() + (cookie_days*24*60*60*1000));
    expires = "expires="+d.toUTCString();
}
//alert('cname ' + cname + 'group ' + cvalue + 'time ' + expires);
document.cookie = cname + "=" + cvalue + "; " + expires;
}

Note that the JavaScript code for setting and resetting a cookie is the same. One caveat is that if the cookie has been set outside of JavaScript, e.g. in PHP, then it is possible that the httponly has been set to TRUE. In that case you cannot modify an existing cookie with JavaScript.

You can get the value of the cookies with this code.


var cookie_name = 'VPA_cor';
var cor = retrieve_cookie(cookie_name);

In my code, I set the cookies with PHP, so the path is already set. If you initialize a cookie with JavaScript, you can set the path by adding a path parameter.


 document.cookie = name + '=' + value + ';' +
                   'expires=' + expires + ';' +
                   'path=' + path + ';';

Browser Cookies with PHP

PHP
Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace. PHP.net

Here is an example of a cookie that checks to see how many times a person has visited the site. Note that it expires in 30 days.


$cookie_name = "VPA";
$cookie_days = 30;
$cookie_time = time()+60*60*24*$cookie_days;
$cookie_path = '';
$cookie_domain = '';
$cookie_secure = false;
$cookie_httponly = true;

if( !isset($_COOKIE[$cookie_name]) ) {
    $cookie_value = 0;
} else {
  $cookie_value = $_COOKIE[$cookie_name] + 1;
}
setcookie($cookie_name,$cookie_value,$cookie_time,$cookie_path,$cookie_domain,$cookie_secure,$cookie_httponly);

In your code you can check for the value of the cookie like this:


echo "Cookie VPA is $_COOKIE[VPA]";

The value can be a number or text. Once a cookie is created, you can update the value in the body of your code.


setcookie("VPA","red",$cookie_time);
echo $_COOKIE["VPA"];

Not that I switched from a number to alpha in this example. The cookies don’t care what the value is or if the type changes. Note that you cannot get the cookie expiration time. And if you leave it off in your setcookie, it will be reset to Session.

To get rid of a cookie, set its value to null and time to something in the past—zero works.


setcookie($cookie_name,'',0);
e.g.
set cookie('VPA','',0);

Beginning jQuery

I’m working on a game and I think I could use some jQuery to make it easier to write. So I visited the jQuery Learning Center to get an overview of the library.

There are lots of examples of the code, but I need to actually write code to see how it works. So I wrote a bunch of code to follow along with the examples that they give. It might be useful to others, so here it is. All of the code is in the php file so if you view source, you will have everything I used.