Archive

Archive for March, 2009

PHP foreach Equivalent In JavaScript

March 31st, 2009 Tech No comments

If you are familiar with PHP you will have come across the forloop at some point. When learning JavaScript it is important to remember that it also has the ability to do the equivalent of the PHP forloop.

The following snippet shows the creation of an array of things that can’t be referenced by a normal for loop due to the odd numbering of the keys.

var arrThings= new Array();
 
arrThings[3] = 'thing 1';
arrThings[42] = 'thing 2';
arrThings[47] = 'thing 3';
arrThings[32] = 'thing 4';
 
var output = '';
 
for ( var thing in arrThings ) {
 output += arrThings[thing];
}
alert(output);

The variable thing is now the iterator and will iterate through each element of the array. By using this code you no longer have to include code that thinks about the length of the array.

Categories: JavaScript Tags: , , , , ,

MySQL Event Scheduler

March 30th, 2009 Tech No comments

A new feature in MySQL version 5.1.6 is the addition of events. These can be either a single event or a schedule, both of which can be given multiple commands to run.

First, you need to make sure that the event scheduler is running. To do this, open up MySQL query browser (or similar) and run the following MySQL command.

SHOW PROCESSLIST;

If the event scheduler you will see a row in the output that looks like this:

Id, User, Host, db, Command, Time, State, Info
120, 'event_scheduler', 'localhost', '', 'Daemon', 242, 'Waiting on empty queue', ''

Turning the event scheduler on and off is quite straightforward and can be done as a MySQL command, or as a parameter when starting the server, or even in an ini file. To turn the scheduler on as a MySQL command run the following:

SET GLOBAL event_scheduler = ON;

Conversely, to turn it off, run the following:

SET GLOBAL event_scheduler = OFF;

To turn it off when you start the MySQL server use the following parameter. Exchange DISABLED with ENABLED to turn it on.

--event-scheduler=DISABLED

To turn it off in the ini file use the following. Exchange DISABLED with ENABLED to turn it on.

event_scheduler=DISABLED

For all instances of controlling the event scheduler you can also use 0 to turn it off and 1 to turn it on instead of DISABLED and ENABLED. You can add and alter events when the scheduler is turned off, but the events will not be run until the scheduler is enabled.

To create an event you need to use the CREATE EVENT command. Lets start off by creating a single event that adds a row to a table called test in the test database at a specified time in the future. The event is called addTimestamp and the command that inserts data is after the DO command. This doesn’t have to be on a separate line, but it looks better and will makes sense when you start adding multiple commands.

CREATE EVENT addTimestamp
 ON SCHEDULE AT '2009-03-30 10:20:00'
 DO
  INSERT INTO test.test(timestamp) VALUES (UNIX_TIMESTAMP());

Note that you need to use

If you create an event in the past you will get the following message.

Event execution time is in the past and ON COMPLETION NOT PRESERVE is set. The event was dropped immediately after creation.

Note that this does not run your command, MySQL will just throw away your event and do nothing. The ON COMPLETION NOT PRESERVE setting tells MySQL to either save the event when it has been run, or to throw it away when complete. To save the event after it has been run add the following line underneath the ON SCHEDULE line.

ON COMPLETION PRESERVE

If you set this and try to create another event of the same name you will get an error stating that the name already exists, even if the old even is in the past.

To insert multiple MySQL commands you need to use the BEGIN and END commands. The following command builds upon the previous example, except this time the table is truncated (cleared) and a new timestamp is added.

delimiter |
 
CREATE EVENT addTimestamp
 ON SCHEDULE AT '2009-03-30 10:28:00'
 DO
  BEGIN
   TRUNCATE TABLE test.test;
   INSERT INTO test.test(timestamp) VALUES (UNIX_TIMESTAMP());
  END |
 
delimiter ;

The delimiter tags tell MySQL to pass the entire block in between BEGIN and END to the server before resetting this to the default and parsing each MySQL command separately.

If you want to run the event in an hour, and don’t want to be tied down to times, then change the ON SCHEDULE line to read the following:

ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR

It is easy enough to see how to change the value of the interval here so I will leave this as an exercise to the reader.

To create an event that occurs every hour you need to change the syntax of the command slightly. Rather than give the SCHEDULE command a time or future interval you use the EVERY command.

delimiter |
 
CREATE EVENT addTimestamp
 ON SCHEDULE
  EVERY 1 HOUR
 DO
  BEGIN
   TRUNCATE TABLE test.test;
   INSERT INTO test.test(timestamp) VALUES (UNIX_TIMESTAMP());
  END |
 
delimiter ;

This can be taken a step further by restricting the window of execution. Lets say we wanted to run a command or set of commands every hour for the next 5 hours. The following commands would be added to the ON SCHEDULE command.

EVERY 1 HOUR
STARTS CURRENT_TIMESTAMP + INTERVAL 1 HOUR
ENDS CURRENT_TIMESTAMP + INTERVAL 5 HOUR

This will cause the commands to be run a total of 5 times.

If you want to know what events or schedules you are currently running the run the MySQL command SHOW EVENTS, this will give you a table full of information. This table will also contain any events that are in the past, but which have had the ON COMPLETION PRESERVE setting added to their creation.

To drop an event you need to run the DROP EVENT command, followed by the name of the event you created.

DROP EVENT addTimestamp;

For more information on the use of the CREATE EVENT syntax please see the MySQL manual page on the subject. There is also more information available on the event scheduler.

PHP Cryptographic Functions For Passwords

March 27th, 2009 Tech No comments

There are three available cryptographic functions in PHP, these are md5(), sha1() and crc32(). All of the functions take a string and output a value that is encrypted and can’t be reversed to the original string. In fact the only way to get the original string back is to run a brute force algorithm which tries to guess what the original string was.

To test these functions I will use the following string.

$string = 'wibble';

md5()

This function returns the hash as a 32-character hexadecimal number. The md5() function is used quite a bit and most PHP programmers will have come across it at some point.

md5($string);
//returns 50eccc6e2b0d307d5e8a40fb296f6171

The md5() and sh1() functions have a second parameter which makes the function return binary data if set to true (the default is false). This returns binary data, which can be turned back into a hexadecimal number by using the bin2hex() function.

bin2hex(md5($string, true));

This function returns the same as in the previous example.

sha1()

sha1() returns the sha1 hash as a string 40 characters long. This function is more secure than the md5() function as there is a lesser chance of guessing what the original string was.

sha1($string);
//returns 02e0182ae38f90d11be647e337665e67f9243817

The sha1() function can also be made to return binary data if the second optional parameter is set to true.

crc32()

This isn’t really a cryptographic function, but it can be used in a similar way as a string will always come out with the same result. This function returns the crc32 polynomial of a string as an integer.

crc32($string);
//returns 489363548

Because of the way that PHP stores integers (as signed), quite a few of the results of this function will be negative. For example, the string "wibble" will return a positive integer, but the string "wobble" will return a negative number, which must be compensated for. This can be fixed by using the "%u" formatter of the sprintf() function, which will return a string containing the correct integer value.

This hashing function is intended to be used as part of a hash table and not as a mechanism of security. This is because it is very easy to generate a "hash collision" where two separate strings have the same hash value. I include this here to give you that warning.

sprintf("%u", crc32($string));
// returns 489363548

crypt()

The crypt() function will take a string as input and produce a variety of different outputs depending on the current system and environment. The salt is the second parameter and if you don’t include this the function will generate a salt for you, which causes the outcome of the hash to be different every time. An important thing to note is that the value of the salt value effects what hashing algorithm is used. There are a set of constants that can be used if you want to detect if an encryption algorithm is available.

if ( CRYPT_STD_DES == 1 ) {
 crypt($string, 'st');
}
// returns something like "stNPuLMaoIxdU"

If you want to compare a password then you must pass the entire result of crypt() as the salt for a crypt of the password. For example, the following is incorrect.

$one = crypt('one');
$two = crypt('one');
var_dump($one == $two); // returns false

Adding a salt to the second crypt() call gives us the correct answer.

$one = crypt('one');
$two = crypt('one', $one);
var_dump($one == $two); // returns true

As with all hashing functions there is no decrypt function as this is a one way process.

hash()

The hash() function is a multi use function that takes two parameters as a default. The first is the hashing algorithm that will be used and the second is the string to be hashed. To encode the string using the whirlpool algorithm use the following code.

hash("whirlpool&quotl, $string);
// returns 91cefc6cc8eecf3a0ef18889bc3b06e7217ce7d41e1d0d5e37709415c3a98e450c53e62ae57680a011a08ef65429e6ba76701c703fcfc4c63938a4aa61737c38

To find out what hashing algorithms your system supports you can use the hash_algos() function. This returns an array of the available algorithms.

print_r(hash_algos());

If you have haval256,5 available in this list then I suggest you use it as it produces the safest hash value. More information about the hash functions can be found in the hash section of the PHP documentation.

Breaking The Code

It isn’t possible to break a md5 of sha1 encoded string, but this can only be done by trying to guess the original value. The site md5.rednoize.com/ can break a string that you enter, but only because it contains 47 million hashes and can therefore reverse engineer the value of the hash.

To stop this happening to your passwords you can use what is called a salt value. Rather than directly encode the value of the password you store the password along with a salt, which is kept secret. An attacker needs to know the value of the salt value before they can correctly guess a users password.

Virtualization With VirtualBox

March 25th, 2009 Tech 2 comments

Virtualization is basically a term used to describe the creation of a computer in software. The main benefits of which are that if you want to try out an operating system or test client server communications you don’t have to get multiple computers. You can simply create a few computers virtually, which will act just like the real thing.

There are quite a few virtualization products available, some are free and some cost quite a bit of money. After messing about with quite a few different virtualisation products other the past few weeks I have uncovered a great bit of software called VirtualBox from Sun Microsystems.

VirtualBox

After installing VirtualBox it took me only a few minutes to set up a new virtual machine. I decided that I wanted to create a virtual machine with Ubuntu installed on it, so I selected the options that optimise VirtualBox for this system. Note that this doesn’t set up a virtual machine with Ubuntu already installed, you have to go and download it yourself! Here is a screenshot of the main interface, which is very easy to understand.

VirtualBox interface

VirtualBox interface

Using virtual machines in the past I have found that to install anything can take a very long time. Installing Ubuntu took not more than 30 minutes, at which point I was presented with the bootup screen.

VirtualBox Ubuntu Boot

VirtualBox Ubuntu Boot

Here is another shot of the operating system fully loaded.

VirtualBox Ubuntu Loaded

VirtualBox Ubuntu Loaded

VirtualBox also supports the creation of snapshots, so if you have a fresh install of an operating system that you want to mess about with (or break) then you can create a snapshot of the virtual machine before you begin. This way, after you trash the system, you can revert back to a snapshot of the system before you started messing about.

The only trouble I had was figuring out how to interface the virtual machine properly with my network, but after reading the documentation this all became very clear.

Overall VirtualBox is a great bit of software, with a detailed and comprehensive manual. I just can’t believe that this software is free!

Display JavaScript Source Programatically

March 23rd, 2009 Tech 2 comments

If you are running a JavaScript example page you can use the following function that will take the last script element on the page and print it out in a code tag. It uses JQuery to do the work, so you will need to include that library before using this function.

<script type="text/javascript">//<![CDATA[
 function displaySource(name) {
  $('<code>'
   + $('#display-' + name).prevAll('script').eq(0).html()
   .replace(/^\s*|\s*$/g, '')
   .split('\n').slice(1, -1).join('\n')
   .replace(/(^|\n) /g, '$1')
   .replace(/('[^']*')/g, '<em>$1</em>')
  + '</code>')
  .insertAfter('#display-' + name);
 }
//]]></script>

The function works by selecting the current script tag and finding all script elements before it. It then selects the first one it finds and outputs the contents to a code tag. It uses a few regular expressions to convert some of the characters to a more human readable format. The function is called like this.

<script type="text/javascript" id="display-test">displaySource("test");</script>