Claudiu Persoiu

Blog-ul lui Claudiu Persoiu


Archive for 11 August 2009

PHP and Unicode using UTF-8

without comments

One of the biggest issues with the web is encoding.

In the old days the formerly base standard was  ISO 8859-1, where there ware 191 latin characters defined, and 1 char = 1B. For different languages, different encodings ware used, but from here many portability issues appeared, the possibility to cover a greater number of languages etc.

The problem occurs when a project should be available in several languages, and the number of the languages is not controlled. A big project like WordPress for example should be available with any language.

Unicode is a better alternative for ISO 8859-1, having more then 100.000 characters defined. In other words it has about every character of about any existing language.

As I was saying for MySQL, UTF-8 characters have a variable length between 1 and 4B.

Displaying the UTF-8 content in PHP pages

For browser to interpret the page content as UTF-8, it should receive the right headers:

<?php header("Content-type: text/html; charset=utf-8");?>

Attention! The header should be the first thing that is send from the server! In other words it should be the first thing displayed on the page.

The type of the document can be specified with the “Content-Type” meta tag. If there is a similar meta tag on the page it should be removed and replace with:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

The .htaccess file and string processing

Add to the .htaccess file (for Apache servers) the following lines:

# default charset used by PHP
php_value default_charset utf-8
# encoding for mbstring
php_value mbstring.internal_encoding utf-8
php_value mbstring.func_overload 7

The first line sets the default charset for PHP, this setting can be made directly to php.ini.

Second and third line sets the mbstring (multi byte string) functions.

Using UTF-8, as I was saying earlier, 1 char != 1B, so errors may appear:

$var = 'aşadar';

echo strlen($var).PHP_EOL; // 7
echo strtoupper($var).PHP_EOL; // AşADAR

// using mbstring functions
echo mb_strlen($var).PHP_EOL; // 6
echo mb_strtoupper($var).PHP_EOL; // AŞADAR

This is why we set the mbstring functions mode using the .htaccess file. Content entered through forms should be processed using mbstring functions, to avoid problems like in the earlier example.

The available functions are in the manual.

Coding old content

There are many ways to encode ISO 8859-1 content to UTF-8. A couple of ways of doing that with PHP are:

iconv() function which converts from a format to another specified format:

echo iconv("ISO-8859-1", "UTF-8", "Test");

utf8_encode() function which converts from ISO 8859-1 to UTF-8:

echo utf8_encode("Test");

What does the future bring?

The long-expected PHP6 will have native support for Unicode, so all the above tricks will be unnecessary. At the moment of writing this blog PHP 6 is 70.70% done, and with a little luck it will be ready in less then an year.

Written by Claudiu Persoiu

11 August 2009 at 10:40 AM

Posted in PHP

Tagged with , , ,

MySQL and Unicode using UTF-8

without comments

Along with globalization, the old ASCII code is no longer suitable.  Consider that one day you have to develop a project in German, Russian or even Japanese, you could adapt the charset for each of these languages or you could simply develop using Unicode.

To use Unicode with MySQL UTF-8 can be used.

You must note that UTF-8 characters are variable in length and they are ASCII compatible. In ASCII 1 char = 1B, in UTF-8 1 char can be between 1 and 4 B.

UTF-8 charset and collation on the server

Character type in MySQL is dictated by charset.

To check if UTF-8 in installed on the server:

SHOW CHARSET LIKE 'utf8';

or with information_schema

SELECT * FROM `CHARACTER_SETS` WHERE CHARACTER_SET_NAME = 'utf8';

If the charset was found then we can continue.

Another element that appears with charset is collation, which it’s used for comparing strings at ordering.

To see what collations are available on the server:

SHOW COLLATION WHERE CHARSET = 'utf8';

or with information_schema

SELECT * FROM `COLLATIONS` WHERE CHARACTER_SET_NAME = 'utf8';

Collation are usually by language, for comparing strings with or without diacritics for example, or “bin” can be used with orders strings in binary mode,  ie “A” is greater than “a” for example.

If no collation is specified, then the default one will be used.

UTF-8 and data bases

When creating a database you can specify the default charset to be used with all new tables for which there isn’t any charset specified.

For example:

CREATE DATABASE db_name CHARACTER SET utf8 COLLATE utf8_romanian_ci;

Or for modifying the default charset for a data base which already exists:

ALTER DATABASE db_name CHARACTER SET utf8 COLLATE utf8_romanian_ci;

UTF-8, tables and columns

For modifying tables which already exist ALTER TABLE must be used is used.

A table can have a default charset and collation, and each column can have it’s own charset and collation.

For more information about the table:

SHOW CREATE TABLE tab;

To set a charset for an existing table:

ALTER TABLE tab CHARSET = utf8 COLLATE = utf8_romanian_ci;

For modifying the charset of a VARCHAR(200) column is used:

ALTER TABLE tab MODIFY c1 VARCHAR(200) CHARSET utf8 COLLATE utf8_romanian_ci;

String size

A “problem” that may arise is related to the size of the character, it’s size can be between 1 and 4B.  That is why for measuring a string column (like varchar) you must use CHAR_LENGTH(str) instead of LENGTH().

A short exemple:

SET @var = 'aşadar';
SELECT CHAR_LENGTH(@var) AS 'Char', LENGTH(@var) AS 'Length';

// The output is: Char = 6 and Length = 7 because ş is 2B

Written by Claudiu Persoiu

10 August 2009 at 1:40 PM

Posted in MySQL

Tagged with , , ,

Generating .CHM manual for Zend Framework using HTML Help Workshop

without comments

If your like me you prefer manuals in CHM format.

Unfortunately Zend Framework manual is only in .pdf and a little less obvious in HTML format.

Fortunately generating a format CHM manual is easy(really, it is).

The steps are:

1. Download and install HTML Help Workshop.

2. Download the Zend Framework manual in HTML format, the link is in bottom right, not very obvious I believe.

3. Open HTML Help Workshop.

4. File->Open and from the folder where the manual files are open htmlhelp.hhp

5. File->Complile

Done!

The compiled CHM manual is just few steps away!

Written by Claudiu Persoiu

9 August 2009 at 10:41 PM

PHP observer pattern and SPL

without comments

Observer pattern refers to a class called “subject” that has a list of dependents, called observers, and notifies them automatically each time an action is taking place.

A small example of why is used:

– let’s say we have a class with does someting:

class Actiune {
    private $val;
    function __construrct() {
        // someting in the constructor
    }

    function change($val) {
        $this->val = $val;
    }
}

Each time $val changes we want to call a method of an “observer” object:

class Actiune {
    private $val;
    function __construrct() {
         // someting in the constructor
    }

    function change($val, $observator) {
        $this->val = $val;
        $observator->update($this);
    }
}

Theoretically is not bad, but the more methods there are so does the dependence grows bigger and each time we add a new observer object we must modify the class, with will probably result in chaos, which will be almost impossible to port.

Now, the observator pattern looks something like this:

diagrama

SPL (Standard PHP Library), which is well known for it’s defined iterators, comes with the interfaces SplSubject and SplObserver, for the subject and respectively the observer.

An implementation looks someting like this:

/**
 * the class which must be monitored
 */
class Actiune implements SplSubject {
    private $observatori = array();
    private $val;

    /**
     * method to attach an observer
     *
     * @param SplObserver $observator
     */
    function attach(SplObserver $observator) {
        $this->observatori[] = $observator;
    }

    /**
     * method to detach an observer
     *
     * @param SplObserver $observator
     */
    function detach(SplObserver $observator) {
        $observatori = array();
        foreach($this->observatori as $observatorul) {
            if($observatorul != $observator) $observatori[] = $observatorul;
        }
        $this->observatori = $observatori;
    }

    /**
     * method that notifies the observer objects
     */
    function notify() {
        foreach($this->observatori as $observator) {
            $observator->update($this);
        }
    }

    /**
     * method for makeing changes in the class
     *
     * @param int $val
     */
    function update($val) {
        echo 'updateing...';
        $this->val = $val;
        $this->notify();
    }

    /**
     * public method with the subject's status
     *
     * @return int
     */
    function getStatus() {
        return $this->val;
    }
}

/**
 * and observer class
 */
class Observator implements SplObserver {
    function update(SplSubject $subiect) {
        echo $subiect->getStatus();
    }
}

// an observer instance
$observator = new Observator();

// an subject instance
$subiect = new Actiune();

// attaching an observer to the subject
$subiect->attach($observator);

// update subject
$subiect->update(5);

What seems strange is that there isn’t any documentation on this SPL interfaces. Even on the Zend website there is an article PHP Patterns: The Observer Pattern which does not use SPL, but for something like namespaces there was documentation even before PHP 5.3 was out.

Written by Claudiu Persoiu

4 August 2009 at 6:52 PM

JavaScript Games

without comments

Today the JavaScript Games section is officially launched! The games have been recently created, after the model of classic games.

I’ve started the first game to show a friend that it is possible to build this kind of apps with JavaScript. And this is one of the main ideas of the section: interactivity in the browser using only HTML, CSS and of course JavaScript!

Today I make them public because is a shame to not give others the chance to waste time playing :).

The games should work cross-browser, they don’t have HTML 5 or other stuff that can lead to incompatibility. They shall prove the power of JavaScript, without any other sophisticated tools.

Many games are not well finished, but I hope that with time I’ll resolve the issues, add new features and of course new games. For suggestions and issues, please send an e-mail to claudiu@claudiupersoiu.ro.

Have fun!

Written by Claudiu Persoiu

2 August 2009 at 7:14 PM

PHP Romanian stemmer class

without comments

Because I needed a Romanian stemmer at a point in time for Zend Search Lucene, and it seems that there aren’t any in PHP, I’ve made one.

The page is here, and  comparing the resulting PHP class with a dictionary of the algorithm developed in snowball,  after which this class was made, because I tried to make class work with or without diacritics, general error has increased by about 3%,  but remaining below 5% for the whole dictionary of 22,570 words.

As a note, the class file should be opened with an UTF-8 editor, otherwise diacritics will disappear from the file.

Enjoy it!

Written by Claudiu Persoiu

1 August 2009 at 1:47 PM

Posted in PHP

Tagged with , ,