Archive

Archive for April, 2009

Validate EAN13 Barcodes

April 30th, 2009 Tech No comments

EAN13 barcodes are commonly used to label products in Europe. If you want to know more about how they work then please view the Wikipedia entry on European Article Numbers.

EAN13 barcodes are actually 12 digits long and are validated by using a check digit, which is placed at the end, making the code 13 digits long. The check digit is worked out by the following process:

  • Add up all of the even numbers and multiply this number by 3.
  • Add up all of the odd numbers and add this result to the result of the even numbers.
  • Divide the number by 10 and keep the remainder (modulo).
  • If the remainder is not 0 then subtract 10 from this number.

Here is a function that runs through those steps, but also check to see what length the barcode is. If it is 13 digits long then it returns both the original check digit and the calculated check digit. If the barcode is 12 digits long then it returns the checksum. In both cases the original barcode is also returned.

function validateEan13($digits)
{
    $originalcheck = false;
    if ( strlen($digits) == 13 ) {
        $originalcheck = substr($digits, -1);
        $digits = substr($digits, 0, -1);
    } elseif ( strlen($digits) != 12 ) {
        // Invalid EAN13 barcode
        return false;
    }
 
    // Add even numbers together
    $even = $digits[1] + $digits[3] + $digits[5] + $digits[7] + $digits[9] + $digits[11];
    // Multiply this result by 3
    $even = $even * 3;
    
    // Add odd numbers together
    $odd = $digits[0] + $digits[2] + $digits[4] + $digits[6] + $digits[8] + $digits[10];
    
    // Add two totals together
    $total = $even + $odd;
    
    // Calculate the checksum
    // Divide total by 10 and store the remainder
    $checksum = $total % 10;
    // If result is not 0 then take away 10
    if($checksum != 0){
        $checksum = 10 - $checksum;
    }
 
    // Return results.
    if ( $originalcheck !== false ) {
        return array('barcode'=>$digits, 'checksum'=>$checksum, 'originalcheck'=>$originalcheck);
    } else {
        return array('barcode'=>$digits, 'checksum'=>$checksum);
    }
}

To test this I ran a few codes through the function.

echo '<pre>';
// two normal barcodes
print_r(validateEan13(5023920187205));
print_r(validateEan13(5010548001860));
// one short barcode to work out checksum
print_r(validateEan13(501054800186));
// a normal barcode
print_r(validateEan13(5034504935778));
// the same barcode with a broken number
print_r(validateEan13(5034504735778));
// two random numbers, one of which is not long enough to be an EA13 barcode
print_r(validateEan13(7233897438712));
var_dump(validateEan13(3345345345));
echo '</pre>';

This prints out the following results, which I have annotated for your convenience.

// two normal barcodes
Array
(
    [barcode] => 502392018720
    [checksum] => 5
    [originalcheck] => 5
)
Array
(
    [barcode] => 501054800186
    [checksum] => 0
    [originalcheck] => 0
)
// one short barcode to work out checksum
Array
(
    [barcode] => 501054800186
    [checksum] => 0
)
 
// a normal barcode
Array
(
    [barcode] => 503450493577
    [checksum] => 8
    [originalcheck] => 8
)
// the same barcode with a broken number
Array
(
    [barcode] => 503450473577
    [checksum] => 4
    [originalcheck] => 8
)
// two random numbers, one of which is not long enough to be an EA13 barcode
Array
(
    [barcode] => 723389743871
    [checksum] => 4
    [originalcheck] => 2
)
bool(false)

Categories: PHP Tags: , , , ,

Create A Tag Cloud Page In Wordpress

April 28th, 2009 Tech No comments

A tag cloud is a name for a collection of keywords that are displayed as a big block of text. Usually the most commonly occurring keyword is the largest, and the least commonly occurring keyword is the smallest. Tag clouds are a neat way of allowing your users to navigate your content in a different way, simply be letting them look over the cloud and linking each keyword to sections of your site that contain that word.

Wordpress comes with this function built in and is already available as a widget. However, after adding a few hundred posts this tag cloud can get rather large and this widget can stretch your sidebar to stupid proportions. A way around this is to create a page that can be used to display this large tag cloud. The first step is to create a page template that will be used to run the correct Wordpress function to display the tags. This is done by making a copy of your normal page template (call it tagpage.php) and adding the following code at the top.

<?php
/*
Template Name: Tags
*/
?>

When you go to create a page you will see a list of available templates to select from, one of these will be called Tags. Add in your title and some descriptive text and select this template.

Next, we need to add a call to the wp_tag_cloud() function, this basically prints out a small tag cloud. Add the following code into your page template so that is fits in with the rest of your design.

<?php wp_tag_cloud(); ?>

As with most Wordpress functions, wp_tag_cloud() allows you to add lots of parameters to change the output of the function. There are lots of different options available, but the main ones that will be used are as follows:

  • smallest - This designates the font size to be used for the least commonly occurring tag. The units are by default in 'pt' or points, but this can be changed via the unit parameter.
  • largest - This designates the font size to be used for the most commonly occurring tag.
  • unit - Unit of measure as pertains to the smallest and largest values. This can be any CSS length value, e.g. pt, px, em, %; default is pt (points).
  • number - This tells the function how many tags to include in the tag cloud. The default is 45, but to print out all tags just use 0.

These parameters are given as an encoded string, for example, to change the number of tags printed from the default of 45 to 20 use the following code.

<?php wp_tag_cloud('number=20'); ?>

Multiple parameters are separated by the & character.

<?php wp_tag_cloud('number=20&largest=200'); ?>

Take a look at the Wordpress manual for more information about the wp_tag_cloud() function

To demonstrate I have created a tag cloud page on Talk In Code, using the following code to create the cloud.

<?php wp_tag_cloud('smallest=7&largest=50&number=500'); ?>

Finally, there is also a function called wp_generate_tag_cloud() that has the same functionality as wp_tag_cloud() but will always return the HTML string that makes the tag cloud.

Hide And Unhide Code With PHP

April 27th, 2009 Tech No comments

If you are selling a system the last thing you want is for people to copy the system and pass it on for free. There are numerous ways to implement parts of the system that will stop this from happening.

By far the easiest is to create a section of code that is hidden, the removal of which will cause the application to fall over. It could even be as simple as a link back to your site so that even if you give you application away for free, you will always have that link present.

This method involves the use of a function called eval(), which takes PHP code as a string and interprets it to produce output. Here is an example that prints a link to Talk In Code.

$code = "echo "<a href='http://www.talkincode.com/' title'Talk In Code'>Talk In Code</a>";";
eval($code);

So lets use some code to hide this from anyone who might be reading our source code. First we pass this string through our hiding function to produce non-human readable text. This function is called obfuscate() and works by taking each character in turn and converting it into the ascii equivalent.

function obfuscate($text) {
    $length = strlen($text);
    $scrambled = '';
    
    for ($i = 0; $i < $length; ++$i) {
        $scrambled .= ord($text[$i]). ' ';
    }
    
    return $scrambled;
}
$code = "echo "<a href='http://www.talkincode.com/' title'Talk In Code'>Talk In Code</a>";";
 
$obf = obfuscate($code);
echo $obf;

This will print out the following:

101 99 104 111 32 34 60 97 32 104 114 101 102 61 39 104 116 116 112 58 47 47 119 119 119 46 116 97 108 107 105 110 99 111 100 101 46 99 111 109 47 39 32 116 105 116 108 101 39 84 97 108 107 32 73 110 32 67 111 100 101 39 62 84 97 108 107 32 73 110 32 67 111 100 101 60 47 97 62 34 59

We can store this as a variable until we next need it. In order to run this code we need to convert it into something that eval() can understand, to do this we use the opposite of the obfuscate(), called unobfuscate(). This function works by taking a set of ascii values and converting them into their character equivalents, note that we also trim the text to remove the last space from the end of the code.

function unobfuscate($scrambled) {
    $text = '';
 
    $bits = explode(' ',$scrambled);
    
    foreach ( $bits as $bit ) {
        $text .= chr($bit);
    }
 
    return trim($text);
}

We can then transform our hidden code into PHP code, which is then passed to the eval() function and run.

$code = '101 99 104 111 32 34 60 97 32 104 114 101 102 61 39 104 116 116 112 58 47 47 119 119 119 46 116 97 108 107 105 110 99 111 100 101 46 99 111 109 47 39 32 116 105 116 108 101 39 84 97 108 107 32 73 110 32 67 111 100 101 39 62 84 97 108 107 32 73 110 32 67 111 100 101 60 47 97 62 34 59';
$code = unobfuscate($code);
eval($code);

This produces the following output.

<a href='http://www.talkincode.com/' title'Talk In Code'>Talk In Code</a>

Beware that doing this sort of thing will probably slow down your application, especially if you try to eval() a large block of code. A single link like this is probably as far as I would personally go as there are much better ways of verifying that a piece of software is properly licensed.

Categories: PHP Strings Tags: , , , , , , ,

Print Array Without Trailing Commas In PHP

April 24th, 2009 Tech No comments

I have previously talked about Removing commas from the end of strings, but it is also possible to use the implode() function to do the same sort of thing.

implode() takes two parameters, the separator and the array, and returns a string with each array item separated with the separator. The following example shows how this function works.

$array = array(1,2,3,4,5,6);
$list = implode(',', $array);

The $list variable will now contain the string "1,2,3,4,5,6". However, things tend to become messy again when you have an array with empty items in it.

$array = array(1,2,3,4,5,6,'','','');
$list = implode(',', $array);

The $list variable will now contain the string "1,2,3,4,5,6,,". So to solve this issue we need to use the array_filter() function to clear out any blank array items before passing the output to the implode() function. The following example shows this in action.

$array = array(1,2,3,4,5,6,'','','');
$list = implode(',', array_filter($array));

The $list variable will now contain the string "1,2,3,4,5,6", which is the string we are looking for.

PHP Array Of Australian States

April 23rd, 2009 Tech No comments

Use the following array to print out a list of Australian states.

$australian_states = array(
    "NSW"=>"New South Wales",
    "VIC"=>"Victoria",
    "QLD"=>"Queensland",
    "TAS"=>"Tasmania",
    "SA"=>"South Australia",
    "WA"=>"Western Australia",
    "NT"=>"Northern Territory",
    "ACT"=>"Australian Capital Terrirory");

Categories: PHP Arrays Tags: , , ,