Programming with PHP and GTK, Part 1

Have you ever thought of writing a PHP application for client side execution without having a web server present? Learn the basics of creating a front end for PHP using PHP-GTK.

Introduction

Have you ever thought of writing a PHP application for client side execution without having a web server present? One of my clients required one of the web applications I had written for him for his website to run on his desktop. Since the whole application was already written, I was dreading the fact that I had to re-code the whole application in another programming language on his desktop.

Since PHP can run from the command line, this got me thinking on how to get the PHP application to run as a windows application. A few searches on Google landed me with the answer to the problem. Combine the programming power of PHP with the GUI’s of GTK (Gnome Tool Kit).

Multi-platform PHP-GTK Extensions

PHP-GTK is an extension to PHP which implements the bindings for the GTK toolkit. This extension allows us to create GUI’s for our PHP applications using GTK+. The present version of PHP-GTK version 1.0 will run under PHP 4.0.5 or greater and GTK+ 1.2.6. Since the present version of PHP-GTK is available for Linux and Windows, the applications you write, will run on both the platforms without any change in code. This is a cool and easy way to write cross-platform applications.

{mospagebreak title=Installing PHP-GTK}

How Do I Install PHP-GTK?

The present version of PHP-GTK is version 1.0.0, which works with PHP4 and GTK+ 1.x. You can download the latest version from http://gtk.php.net/download.php. The present version is supported on Windows and Linux. Here’s how you can install it on your system.

Installing PHP-GTK in Windows

This installation method should work for Windows NT, 2000 and XP. I’m assuming that you have not installed PHP on your system prior to this. Download the zip file with the latest version of PHP-GTK to your system. Use a program like Winzip to extract the files to a temporary folder. For ease of explanation, let’s say you extract the zip file to C:TEMP. When you go to C:TEMP you’ll find 3 folders which have been extracted:

  • PHP4
  • TEST
  • WINNT

The PHP4 folder contains an installation of PHP and GTK libraries required to run PHP-GTK. Copy the PHP4 folder to your C: drive so the path of your PHP4 directory becomes c:php4. The folder c:tempwinnt contains the configuration file for PHP: php.ini. Copy php.ini to your windows directory, either c:windows or c:winnt, depending on your version of Windows. The folder c:temptest contains some test programs for PHP-GTK. You can copy this folder under c:php4. So your test programs will be accessible under c:php4test

If you have a prior installation of PHP, do not copy the php.ini file to your windows folder. You’ll have to manually copy the changes in the supplied php.ini to your original configuration file.The rest of the installation remains the same.

Add C:PHP4 to your file path in the environment variables. Here’s how you get to the environment variables:

Start>Settings>Control Panel>System>Advanced>Environment Variables

We do this so we can call a execute a php script by calling “php script.php” instead of having to supply the path to php.exe every time. If you don’t wish to add the path to PHP4 in the environment variable, you’ll need to call php by using the full path like so – “c:php4php script.php”

{mospagebreak title=A Test Run}

Let’s get to running a program

Before we start learning how to write programs in PHP-GTK, let’s run one of the test programs to see if our installation work. Let’s run a program called hello.php, which is in the TEST folder. Go to the command prompt and head over to C:PHP4TEST. To run the program, you’ll need to type in “php hello.php”.

If your PHP-GTK installation is correct, you should see a new window pop up with a button which greeting Hello World!

PHP and GTK+

You can click on the button to close the program. You’ll notice that when you click on the button, before the program exits, it sends the output “Hello World” back to the command console. If you use echo and print functions in your program, the output goes to the command console instead of the GTK front-end. This feature can be tapped when you need to debug your programs:

C:>cdphp4test
C:php4test>php hello.php
Hello World !

C:php4test>_

Now you can try running the other programs in the test folder.

{mospagebreak title=A PHP-GTK Window}

Making a window

Let’s start off with PHP-GTK programming by making a simple window. Before you start any PHP-GTK code, you’ll need to load the GTK extensions for PHP. This is achieved by using the following code:

if (!extension_loaded(‘gtk’)) {
dl( ‘php_gtk.’ . PHP_SHLIB_SUFFIX);
}

This snippet of code should be present at the start of all your programs using the PHP-GTK extension. What this code does is to load the GTK extension if it’s not already loaded.

Now let’s get to the code to create a window. Let’s create a window with the Title “First Window” and save the code as window.php

<?
if (!extension_loaded(‘gtk’)) {
dl( ‘php_gtk.’ . PHP_SHLIB_SUFFIX);
}

//function to handle destroy signal
function killwindow()
 {
        Gtk::main_quit();
  }

// Create a new Window
$window = &new GtkWindow();
$window->set_title(“First Window”);
$window->set_usize(200, 60);

//Callback for destroy signal
$window->connect(“destroy”, “killwindow”);

// Show the window
$window->show_all();

// Start the main PHP-GTK listener loop
gtk::main();
?>

Does this look cryptic? It’s quite easy to understand. Let’s look at the following snippet of code:

$window = &new GtkWindow();
$window->set_title(“First Window”);
$window->set_usize(200, 60);

The first line $window = &new GtkWindow(); creates a new instance of a GTK Window. The next two lines sets the window properties.

window->set_title allows you to set the Window’s Title, which is the text in the Title Bar.

window->set_usize allows you to set the size of the window. In this example, we are creating a 200×600 window.

Now we come to the the callback function for signal handling. The following line allows you to capture the destroy signal for the window.

//Callback for destroy signal
$window->connect(“destroy”, “killwindow”);

Now what’s a signal? In GTK, any action you take on a components, generates a signal. We need to trap these signals to respond properly to the action. In our window we need to trap the destroy signal, which will be generated when the window is closed. In the above code, we are telling the program to call the function killwindow, when the destroy signal is generated.

function killwindow()
 {
        Gtk::main_quit();
  }

The function killwindow() is used to respond to the destroy signal. Gtk::main_quit() tells GTK to close the program. This is an important step to shut down the program. If you do not call Gtk::main_quit() to shutdown the program, the window might disappear when you close the it, but the application will still be running in the background.

$window->show_all();
gtk::main();

These two lines are important to your code. The first line $window->show_all(); tells the program to display your window. If you do not call this code, the window will not appear on screen. The next line, gtk::main(); is the GTK event loop. This loop keeps running till Gtk::main_quit() is called.

Now when you run this program window.php, you should get an output like this:

PHP and GTK+

{mospagebreak title=Widgets}

Widgets in GTK

What are widgets?

Widgets are data structures which house information about a user-interface objects. This in simple terms mean user-interface objects like buttons, text boxes, windows and combo-boxes.

So let’s see how we can create such widgets. To house these widgets, you’ll need to create a GTK container. This container can be either vertical (GtkVBox) or horizontal (GtkHBox). In GtkHBox, all the widgets will align horizontally, while it will align vertically in the case of GtkVbox. We’ll create a vertical container for our program.

// Add a GtkVBox class to our window
$box = &new GtkVBox();
$window->add($box);

Let’s add a text entry widget to this box:

// Add a GtkEntry class to our window
$entry = &new GtkEntry();
$entry->set_text(“Play with Strings”);
$box->pack_start($entry);

The above code creates a new GtkEntry widget, sets the text in the field to “Play with Strings” and adds it to the box. The code $box->pack_start($entry); is used to add the entry to the already created box. You can skip the $entry->set_text(“Play with Strings”) if you do not want to initialize the text and want a blank entry field.

Now let’s add a button:

// Add a GtkButton class to our window
$button = &new GtkButton(“Buttontext”);
$button->connect(“clicked”, “buttonfunction”);
$box->pack_start($button);

This button which is created will have the text “Buttontext” on it. When the button is clicked, the function “buttonfunction” will be called to handle the click. Now how about a tool tip when the mouse hovers over the button?

$tt = &new GtkTooltips();
$tt->set_delay(200);
$tt->set_tip($widget, ‘Here’s a Tip’, ”);
$tt->enable();

You can set the Tooltips delay using $tt->set_delay(200) where 200 is amount of delay after which the tooltips will be displayed. You can set tool tips for each widget separately.

{mospagebreak title=A Simple Program}

Now that we know how to create windows and widgets in PHP-GTK, let’s go on to make a simple program. Let’s put these all together in a program which will allow you to enter a string in a Entry field, when the Button “UpperCase” is clicked, the string will be converted to uppercase and displayed back in the Entry field and when the button “LowerCase” is clocked, the string will be converted to lowercase and displayed.

<?php

if (!extension_loaded(‘gtk’)) {
dl( ‘php_gtk.’ . PHP_SHLIB_SUFFIX);
}

function UCText($theButton, $theEntry)
{
   $text = strtoupper($theEntry->get_text());
   $theEntry->set_text($text);
}

function LCText($theButton, $theEntry)
{
   $text = strtolower($theEntry->get_text());
   $theEntry->set_text($text);
}

function destroy()
{
     gtk::main_quit();
}

// Create a new window
$window = &new GtkWindow();
$window->set_title(“Play with Strings”);
$window->set_usize(300, 60);
$window->set_border_width(3);
$window->set_position(GTK_WIN_POS_CENTER);
// Set a callback function for the destroy signal
$window->connect(“destroy”, “destroy”);

// Add a GtkVBox class to our window
$box = &new GtkVBox();
$window->add($box);

// Add a GtkEntry class
$entry = &new GtkEntry();
$entry->set_text(“Play with Strings”);
$box->pack_start($entry);

// Add UpperCase GtkButton
$button1 = &new GtkButton(“UpperCase”);
$button1->connect(“clicked”, “UCText”, $entry);
$box->pack_start($button1);

// Add LowerCase GtkButton
$button2 = &new GtkButton(“LowerCase”);
$button2->connect(“clicked”, “LCText”, $entry);
$box->pack_start($button2);

//Tooltip for Uppercase Button
$tt1 = &new GtkTooltips();
$tt1->set_delay(200);
$tt1->set_tip($button1, ‘Click here to Convert to Uppercase’, ”);
$tt1->enable();

//Tooltip for Lowercase Button
$tt2 = &new GtkTooltips();
$tt2->set_delay(200);
$tt2->set_tip($button2, ‘Click here to Convert to Lowercase’, ”);
$tt2->enable();

// Show the window
$window->show_all();

// Start the main PHP-GTK listener loop
gtk::main();

?>

You’ll notice I’ve added some extra calls while creating the window. Here’s what they are:

    * $window->set_border_width(3) : This sets the window border to 3. This is to ensure that the widgets to expand to the fill size of the window.
    * $window->set_position(GTK_WIN_POS_CENTER) : This sets the window position to the center of the screen.

Let’s analyze the function UCText.

function UCText($theButton, $theEntry)
{
   $text = strtoupper($theEntry->get_text());
   $theEntry->set_text($text);
}

This when this function is called, the instance of the Entry Widget is passed to this function. This allows us to access the text in the Entry Widget. The text is converted to uppercase using the PHP function strtoupper, and the text is stored back into the Entry Widget. The function LCText also functions the same way. Now how did I pass the instance if the Entry Widget to this function? If you look at the callback function for the button clicked signal, I’ve added $entry to the connect function to pass the instance if $entry to these functions

$button1->connect(“clicked”, “UCText”, $entry);
$button2->connect(“clicked”, “LCText”, $entry);

Now let’s save and run this program to see how it works. As soon as you run this program, you’ll get a window quite similar to this:

PHP and GTK+

Click on the Uppercase and LowerCase buttons to see the text in the Entry Widget change. You can also edit the string in the Entry Widget and click on the buttons to see your text change.

Now that we’ve covered the basics of creating a front end for PHP using PHP-GTK, you can experiment with this and start creating stand-alone PHP applications for Windows and Linux. In the next part of this series I’ll be showing you how to create database applications using PHP-GTK.

[gp-comments width="770" linklove="off" ]

chat