Test your code with xhprof

Sometimes we try to optimize our code even before testing it. It’s good to use the best practices, but we also should test our application with profiling tools. One of the best of them out there in open source world is xhprof that was created by Facebook and went open source. I’ve started to use it recently and it really helps at code optimisation research.

If you want to start looking at xhprof, then you should start by reading this article/tutorial (http://techportal.ibuildings.com/2009/12/01/profiling-with-xhprof/) . You will see how simple and efficient xhprof is.

Also xhprof comes with a GUI for profiling visualisation, but it is not so nice and don’t have a lot of features, so my suggestion would be to use this (https://github.com/preinheimer/xhprof) GUI, that is much nicer and have more features.

The entity “Atilde” was referenced, but not declared.

While using SalesForce API to upsert data to SalesForce I’ve got an error “The entity “Atilde” was referenced, but not declared.”. I found out that the problem causing this error was htmlentities php function. htmlentities converts all applicable characters to HTML entities. html_entity_decode php function solved the problem so don’t use htmlentities, try to change this function with htmlspecialchars if you want to sanitize html for salesforce.

PHP recursive menu with 1 query

There are a lot of methods how to fetch menu with submenus. But I will show you how to get all menu with submenu data from database in one query and make recursive display with PHP.

Table “menu” schema should look like this:

id parent_id title
73 0 MENU_73
74 73 MENU_73_74

When we fill the database with menu/submenu records we can get all records by query:

$query = mysql_query("SELECT * FROM menu");

After printing query results we should see:

Array
(
    [0] => Array
        (
            [id] => 73
            [parent_id] => 0
            [title] => MENU_73
        )

    [1] => Array
        (
            [id] => 74
            [parent_id] => 73
            [title] => MENU_73_74
        )

    [2] => Array
        (
            [id] => 75
            [parent_id] => 74
            [title] => MENU_73_74_75
        )

    [3] => Array
        (
            [id] => 76
            [parent_id] => 74
            [title] => MENU_73_74_76
        )

    [4] => Array
        (
            [id] => 77
            [parent_id] => 74
            [title] => MENU_73_74_77
        )

    [5] => Array
        (
            [id] => 78
            [parent_id] => 73
            [title] => MENU_73_78
        )

    [6] => Array
        (
            [id] => 79
            [parent_id] => 78
            [title] => MENU_73_78_79
        )

    [7] => Array
        (
            [id] => 80
            [parent_id] => 73
            [title] => MENU_73_80
        )

    [8] => Array
        (
            [id] => 84
            [parent_id] => 80
            [title] => MENU_73_80_84
        )

    [9] => Array
        (
            [id] => 85
            [parent_id] => 80
            [title] => MENU_73_80_85
        )

    [10] => Array
        (
            [id] => 81
            [parent_id] => 0
            [title] => MENU_81
        )

    [11] => Array
        (
            [id] => 82
            [parent_id] => 81
            [title] => MENU_81_82
        )

    [12] => Array
        (
            [id] => 83
            [parent_id] => 81
            [title] => MENU_81_83
        )

)

We want to get those result with assigned childrens to parent, so use this function to do that:

//$tree - menu data array
//$parent - 0
function formatTree($tree, $parent){
        $tree2 = array();
        foreach($tree as $i => $item){
            if($item['parent_id'] == $parent){
                $tree2[$item['id']] = $item;
                $tree2[$item['id']]['submenu'] = formatTree($tree, $item['id']);
            }
        }

        return $tree2;
    }

And the result of using recursive function:

Array
(
    [73] => Array
        (
            [id] => 73
            [parent_id] => 0
            [title] => MENU_73
            [submenu] => Array
                (
                    [74] => Array
                        (
                            [id] => 74
                            [parent_id] => 73
                            [title] => MENU_73_74
                            [submenu] => Array
                                (
                                    [75] => Array
                                        (
                                            [id] => 75
                                            [parent_id] => 74
                                            [title] => MENU_73_74_75
                                            [submenu] => Array
                                                (
                                                )

                                        )

                                    [76] => Array
                                        (
                                            [id] => 76
                                            [parent_id] => 74
                                            [title] => MENU_73_74_76
                                            [submenu] => Array
                                                (
                                                )

                                        )

                                    [77] => Array
                                        (
                                            [id] => 77
                                            [parent_id] => 74
                                            [title] => MENU_73_74_77
                                            [submenu] => Array
                                                (
                                                )

                                        )

                                )

                        )

                    [78] => Array
                        (
                            [id] => 78
                            [parent_id] => 73
                            [title] => MENU_73_78
                            [submenu] => Array
                                (
                                    [79] => Array
                                        (
                                            [id] => 79
                                            [parent_id] => 78
                                            [title] => MENU_73_78_79
                                            [submenu] => Array
                                                (
                                                )

                                        )

                                )

                        )

                    [80] => Array
                        (
                            [id] => 80
                            [parent_id] => 73
                            [title] => MENU_73_80
                            [submenu] => Array
                                (
                                    [84] => Array
                                        (
                                            [id] => 84
                                            [parent_id] => 80
                                            [title] => MENU_73_80_84
                                            [submenu] => Array
                                                (
                                                )

                                        )

                                    [85] => Array
                                        (
                                            [id] => 85
                                            [parent_id] => 80
                                            [title] => MENU_73_80_85
                                            [submenu] => Array
                                                (
                                                )

                                        )

                                )

                        )

                )

        )

    [81] => Array
        (
            [id] => 81
            [parent_id] => 0
            [title] => MENU_81
            [submenu] => Array
                (
                    [82] => Array
                        (
                            [id] => 82
                            [parent_id] => 81
                            [title] => MENU_81_82
                            [submenu] => Array
                                (
                                )

                        )

                    [83] => Array
                        (
                            [id] => 83
                            [parent_id] => 81
                            [title] => MENU_81_83
                            [submenu] => Array
                                (
                                )

                        )

                )

        )

)

Now it is easy to print this array to menu with submenu.

PHP tips and tricks

There are a lot of php tips or tricks that you may don’t know. So I want to share with you with tips that I know. Some of them can help a lot and some of them are to write less code. Here is a list of tips and tricks:

1. Did you know you can write a variable in a string with double quote and php will print it as variable?

$variable = 'ADD ME';
$text = "So here is $variable and some text";
echo $text; // output: So here is ADD ME and some text

//other method with brackets
$variable['add'] = 'ADD ME';
$text = "So here is {$variable['add']} and some text";
echo $text; // output: So here is ADD ME and some text



2. Did you know what is difference between quote (‘) and double quote (“) in php (look at $text)?

$variable = 'ADD ME';
$text = 'So here is $variable and some text';
echo $text; // output: So here is $variable and some text

$variable = 'ADD ME';
$text = "So here is $variable and some text";
echo $text; // output: So here is ADD ME and some text



3. Did you know how to write shorter IF/ELSE ?

//original
if($hey){
   echo 'hey';
}else{
   echo 'bye';
}

//short method
echo ($hey)?'hey':'bye';



4. Did you know you can assign variable and check in IF statement at the same time with one = ?

if($ok = $this->getOk()){
   echo $ok; //if $ok is not empty or false it will echo $this->getOk() value
}



5. Did you know you can create a function on the fly ( http://lt.php.net/create_function )?

$sumfunction = create_function('$a,$b', 'return $a + $b;');
echo $sumfunction(3, 2); //output: 5



6. Do you know that true === 1 is equal to false, because === is not the same as == ?

if(true === 1) //will result in false
if(true == 1) //will result in true
//because === will check type also



7. Do you know that @ near variable will suppress php warning messages ?

echo $variable; //will result in warning message, because $variable is not defined
echo @$variable; //no warning message



8. Do you know that echo is faster than print and quote is faster than double quote ?


I will add some more tips and tricks later.

How to get youtube image/thumbnail

I’ve got a spare time of half a day and thought about making a website of funny videos for myself. I love my custom CMS, because all coding goes fast like saying to a computer do that, do that and voila! But this post is not about my CMS.

Most of videos will be posted from YouTube, so I thought why not to make YouTube video image/thumb uploading automatically, to save some time while adding content.
First of all I need to get YouTube video ID from URL like this http://www.youtube.com/watch?v=oHg5SJYRHA0&feature=relate. Fastest and the best method in my opinion is:

$url = "http://www.youtube.com/watch?v=oHg5SJYRHA0&feature=relate";
parse_str( parse_url( $url, PHP_URL_QUERY ) );
echo $v; // this will output oHg5SJYRHA0

OK so now we have YouTube video ID. Each YouTube video has 4 generated thumbnails. You can find them at:

http://img.youtube.com/vi/videoID/0.jpg

http://img.youtube.com/vi/videoID/1.jpg

http://img.youtube.com/vi/videoID/2.jpg

http://img.youtube.com/vi/videoID/3.jpg

Just put video id that we got it before, to the place where videoID is. The URL with my example should look like http://img.youtube.com/vi/oHg5SJYRHA0/0.jpg.

First image is always default and biggest image.

encoding ASCII to 7bit strings and decoding

I am working now with Lithuanian mobile operators to implement Unstructured Supplementary Service Data (USSD). Messages must be encoded in utf7, so I would like to share encoding ASCII to 7bit strings and decoding 7bit to ASCII functions that my colleague helped to write.

/**
 * encoding ASCII to 7bit strings
 * @param string $text
 * @return string
 */
function encode7bit($text){
	$ret = '';
	$data = str_split($text);
	$mask = 0xFF;
	$shift = 0;
	$len = count($data);
	for ($i = 0; $i < $len; $i++) {
		$char = ord($data[$i]) & 0x7F; // only 7bits
		$nextChar = ($i+1 < $len) ? (ord($data[$i+1]) & 0x7F) : 0; // only 7bits
		if ($shift == 7) { $shift = 0; continue; }
		$carry	= ($nextChar & ((($mask << ($shift+1)) ^ 0xFF) & 0xFF));
		$digit = (($carry << (7-$shift)) | ($char >> $shift) ) & 0xFF;
		$ret .= chr($digit);
		$shift++;
	}
	$str = unpack('H*', $ret);
	return strtoupper($str[1]);
}
/**
 * decoding 7bit strings to ASCII
 * @param string $text
 * @return string
 */
function decode7bit($text){
	$ret = '';
	$data = str_split(pack('H*', $text));

	$mask = 0xFF;
	$shift = 0;
	$carry = 0;
	foreach ($data as $char) {
		if ($shift == 7) {
			$ret .= chr($carry);
			$carry = 0;
			$shift = 0;
		}

		$a	=	($mask >> ($shift+1)) & 0xFF;
		$b	=	$a ^ 0xFF;

		$digit = ($carry) | ((ord($char) & $a) << ($shift)) & 0xFF;
		$carry = (ord($char) & $b) >> (7-$shift);
		$ret .= chr($digit);

		$shift++;
	}
	if ($carry) $ret .= chr($carry);
	return $ret;
}

Again IE! session refresh

Again problems with IE (Internet Explorer). Grrr how I hate it. Can we count IE as browser? I never say it is browser, I just say that website works on browsers and IE… This time the problem with IE is about sessions. On IE refresh every time session_id changes. Few hours of headbanging to keyboard and I have found a solution.

There’s a bug in Internet explorer in which sessions do not work if the name of the server is not a valid name. For example…if your server is called web_server ( _ isn’t a valid character), if you call a page which uses sessions like http://web_server/example.php your sessions won’t work but sessions will work if you call the script like this
[IP NUMBER]/example.php

At http://www.php.net/manual/en/ref.session.php#81641

The problem was “_”.

jquery/php ColoXY game

About 2 years ago I’ve made my first game with jquery. Almost forgot about it. It was made in about 1 day. The game is very simple and have some similarities to cubic rubic (the magic cubic of rubic), just it is in 2D and have 5 planes. Because I couldn’t find a game like this, I’ve named it ColoXY. There was a better, nicer version of game with highscores, but after hard drive format I was unable to find a latest version.

The game is made with php/javascript/jquery/html/css. Graphics are made in photoshop. It is using client/server architecture, when backend making all calculations and client  gets only data where to move, so there are no posibility to cheat on this game :)   Communication is done with ajax.

Instructions

To win this game, you need to mix the lines in order to make all 5 boxes the same color. Click arrows around the middle box with your mouse.

Where to find

You can find it here http://jugbit.com/jquery/coloxy/

Forgot to mention that I’ve made a flash version of this game also. You can find it on kongregate http://www.kongregate.com/games/kasp3r/coloxy

Where is source?

You can grab all source code by going to http://jugbit.com/jquery/coloxy/coloxy.zip

License?

No license or some other restrictions like always. Use it, modify it how you like, but at least it would be cool if you leave original author comment in source code.

jquery plugin tutorial requests

Today i’ve got an idea to make a request section. Maybe you need some plugin or tutorial that you can’t find on google, but you really need it? Post a comment and I will try to help you. Request for a plugin, tutorial, tip or other similar task. Try to write as much information as you can about your request. I promise that all of you will get my reply.

Netbeans utf-8

Today I started to use Netbeans for PHP development. Everything seems ok and works faster than zend studio, BUT! When I tried to open a php file I’ve noticed that there was no utf8 support. I was looking all over the options and had to head bang the wall till I got an idea to check the best source for all questions. Google! . Voila I’ve found an answer in a second search result. It seems that there are no such option to change encoding. You need to edit neatbeans config file. So if you got the same problem you need to go to netbeans -> etc and open netbeans.conf file. There on the line netbeans_default_options add -J-Dfile.encoding=UTF-8 and all your files will open in utf8 by default. If you get error when try to save file that this file is opened in other programa bla bla bla and you can’t save, then run text editor as administrator. Save file, open netbeans and file that should be utf8. Yay it works!