The “hello world” example is of course inevitable but seeing the line “hello world” printed in a browser actually takes a lot of preparation involving at least HTTP and DNS. Why not make a start with command-line PHP instead.

Take any server running with a Linux operating system, gain access to the command-line and type:

php -v

The server responds with information on the PHP version and if postfixed by “(cli)” the PHP Command Line Interface is installed.

Next, for the location of the PHP executable type

which PHP

The response will tell you where the PHP executable resides, for example the response may look like this:

/usr/local/bin/php

More information is extracted by typing

whereis PHP

which could result in

php: /usr/local/bin/php /usr/local/lib/php /usr/local/lib/php.ini

executing a line of PHP code should be as simple as this:

php -r ‘echo “hello world\n”;’

returns

hello world

The only requirement being that the path /usr/local/bin is listed in the preferred PATH variable of the local ENVIRONMENT.

Print the environment on the command-line with the command:

printenv

and the path should be listed in the PATH section.

The whereis PHP command also gives away the location of the php.ini file which is the main PHP configuration file. The content of this file can be retrieved by invoking PHP itself

php -r ‘phpinfo();’

or simply by the vi editor

vi /usr/local/lib/php.ini

On the command-line PHP is just like any other unix command, it even comes with a man page:

man php

The PHP -r switch used thus far will allow the command to run directly. Another switch is -f which will execute a file containing PHP script as in:


touch index.php;
 echo '<?php echo "hello world\n";' > index.php;
php -f index.php;

This action introduces the “opening tag” phenomenon. The rules are simple: any php file is opened by the <?php declaration and closing a file with ?> is optional.

The opening tag tells the program how the interpret the code. The <?hh tag specifies Hack and the <?asp tag specifies ASP. Leaving out the opening tag in this example will simply print the code but not execute it.

PHP can also be run as an executable program, a so-called bash-script. The index.php file now requires a so-called shebang as the first line:

#!/usr/local/bin/php
<?php
echo “hello world\n”;

The shebang line tells the program loader what interpreter to deploy. Next the file needs to be executable. Type on the command line:

chmod +x index.php

The file can now be run as:

./index.php

The ./ in this command means that the index.php script can be found in the current directory. The alternative would be to use the full directory path as in /full/path/to/script/index.php