samedi 31 janvier 2015

Compile Your PHP Code

PHP is known as a web programming language, but guess what ! it is a fully language that it can be used like Java, C, python... or any other client side language.

In my first tutorial, i will learn you, with a simple example, how you can do that.

Let's start by some configuration :

1 - Download PHP (if you have not a PHP installed in your machine, or if you want to do some upgrade) : http://php.net/downloads.php
2 - Extract the downloaded archive in your chosen folder.
3 - Add PHP folder to your environemnt variable PATH (same variable name on Windows/Linux/MacOs)
4 - Open a command prompt and type : php --version

You should see the version of the installed PHP
Now, create this simple PHP source, i will suppose that it will be C:\test.php
We will write a code that will do the sum of two values that will be given in arguments :

<?php
printf ("\nHello, You are using PHP Like C.\n");
printf ("----------------------------------\n");

if (count($argv) != 3 || is_numeric($argv[1]) || !is_numeric($argv[2])) {
    printf ("Expecting 2 valid numbers...try again :)\n");
    exit (0);
}
printf ("%d + %d = %d\n", $argv[1], $argv[2], $argv[1] + $argv[2]);
printf ("See you next time :)\n");
printf ("----------------------------------\n");

?>

Now, open a command prompt and type :
php C:\test.php 5 15
If all it is ok, you should see the sum of 5 and 15

Ok, it is good to know that we can use PHP code in client side, like a true programming language, but if i want to run my script on another machine, i must install PHP on it ?
The response, is no :)

Let's continue our configuration :

5 - Download Phalanger from this URL : http://phalanger.codeplex.com/
5 - Install it on your machine.
6 - On Windows, you can see a new shortcut added in your start panel : "Phalanger Command Prompt". Click on it.
7 - Compile your PHP code using this command : phpc.exe C:\test.php

Now you will find your compiled test.php script as test.exe under Phalanger_Installation_Path/Bin/bin

In my case test.exe is located under : C:\Program Files (x86)\Phalanger 3.0\Bin\bin

Open a command prompt under this path and type test.exe 5 15

All done ! now you know that you can build a whole applicatin with PHP and distribute it easily :)

My configuration :
 - Windows 7 Professional 64 Bits
 - PHP 5.5.11 (cli) (built: Apr  8 2014 15:07:14)
- Phalanger 3.0

See you next time :)
Anis