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.

Perl gotcha’s–arrays

Working with some existing code to pull data from a MySQL database I ran the following code:


$SQL  = "SELECT id FROM `sensors` ";
$SQL .= "WHERE `storage_table` LIKE '$source_temperature_table' ";

$r = $db->query($SQL);
my $src_sensor_id = $r->getNextRow();
print "The id is $src_sensor_id \n";

No matter which table I ran this on, I always got 1 as the id. So I tried looking at the value of $r using print $r; and the correct ID was showing up. The reason is that perl is different from other languages that I use when it comes to arrays. When I thought I assigned the only value in $r to $src_sensor_id, what I was really doing was assigning the count of the number of rows in $r to $src_sensor_id. When I printed $r, the print statement printed all of the values in the array $r because that’s how print statements handle arrays.

The correct way to assign the array values in $r to variables is to put parentheses around the list of variables in the array. e.g.


my ($src_sensor_id) = $r->getNextRow();

If you have multiple items in the array, separate the variables with commas. e.g.


my ($src_sensor_id, $location, $name) = $r->getNextRow();

Is the server alive?

I’ve been working on a server that has been going offline. I can tell it’s offline because I get an indicator in my mail program that shows that I can’t get mail. The first time it happened we called over to the data center and had them restart everything. That worked for a while but then it happened again. This time we went over to the data center and the server itself was fine. Replacing the switch that connected two servers made the problem go away. A few weeks later, the server went offline again. This time it looked like it was a DDOS. It has been fine ever since, but we wanted to have a better way of knowing that there is an issue than me happening to look at my email program and noticing that I wasn’t getting mail.

One way to see if it is alive is to ping the server every few minutes. If I get no response, then send a text to the owner and an email to me.

I have a couple of cron job on my server running under my crontab that send out notifications by text or email every minute. So I edited the crontab to add another job to its list.

To see the cron jobs, crontab -l -u myuserid. To edit type, crontab -e.


# m h  dom mon dow   command
*/1 * * * * /home/myuserid/reminder.sh
*/1 * * * * /home/myuserid/ping_remote_server.sh

Here’s the shell script I wrote to ping the server and send out notifications.


#!/bin/sh
ping -c 1  -q remoteservername.com  1>/dev/null 2>&1;
return_code=$?;

if [ $return_code -ne 0 ]; then
    #echo "Failure";
    mail -s "Server Down"  8055551212@mobile.mycingular.com myuserid@MyServer.com < /dev/null
fi

I ping it once (-c 1), quietly—since I don’t care about the result (-q) and send the result and any error messages to /dev/null. All I care about is whether it was successful. Every Linux command has an exit status code. You can access it with $?. I only care if the command ran successfully, so I check to see if it is not 0.

I don’t need any details in the text that I send, so I set the subject and grab the content from