Home > Articles > Programming > PHP

PHP Basics: Writing Simple PHP Applications

  • Print
  • + Share This
  • 💬 Discuss
Ewald Geschwinde and Hans-Juergen Schoenig discuss how to write simple PHP applications. Learn the basics of PHP syntax as well as PHP's built-in functions.

PHP is an easy language and you'll find it an easy task to get used to PHP. In this chapter you learn to write simple PHP applications. You learn the basics of PHP syntax as well as PHP's built-in functions.

3.1 Getting Started

In this section you learn to write simple applications. The basics of PHP's interpreter are also covered in detail.

3.1.1 "Hello World"

The first application you will find in most books about computer programming is "Hello World". "Hello World" is easy to implement in all languages because it does nothing except print a string on the screen, so it is a good start. Here is the easiest version of "Hello World" written in PHP:

<?php
    echo 'hello world<br>';
?>

With just three lines of code, you can print a simple message on the screen. The first line of code tells the Web server that the next lines of code have to be executed by the PHP interpreter. ?> means that the code ends here. Using <?php is not the only possible way to tell the Web server that PHP code has to be executed. PHP provides three additional ways to escape from HTML:

<?
    echo 'hello world 1<br>';
?>
 
<script language="php">
    echo 'hello world 2<br>';
</script>
 
<%
    echo 'hello world 3<br>';
%>

In the first three lines, you can see that it is not necessary to mention that the PHP interpreter has to be called. This method of escaping HTML is possible only when short tags are enabled (you can do this by setting the short_open_tag option in PHP's configuration file). However, to make clear which programming language is meant, we recommend using <?php instead of <?.

The third method can be used if Active Server Pages (ASP) tags are enabled. If ASP tags are turned off, <% and %> will be treated like ordinary text and the PHP code will not be interpreted. Therefore we recommend using either <?php or <script language="php"> to tell the Web server what to do with the PHP code. In this book we will use <?php to escape HTML.

If you have put the file containing the code into the right directory (see the documentation and configuration of your Web server to find the right directory), you can execute the script by accessing it in your Web browser. If the file is called hello.php and if it is in the default HTML directory of your local machine, it can easily be accessed by using http://localhost/hello.php. You do not have to add execute rights to the file because the Web server only has to read the file.

If everything has been done correctly, PHP has been configured successfully, and your Web server has been started, hello world will be displayed on the screen.

Your first version of "Hello World" produces just text. However, the main target of a PHP program is to generate HTML code. In the next example, you will see a small script generating the HTML version of "Hello World".

<html>
<head>
    <title>Title of the site</title>
</head>
<body>
    <?php echo 'hello world<br>'; ?>
</body>
</html>

As you can see, the PHP code is included in the HTML code. <?php tells the server that the PHP interpreter has to be started here. In the example you can see that parts of the document are static and other parts of the document are created dynamically by PHP.

Another way to obtain the same target would be to generate the entire document dynamically. This will be slower than the version you have just seen, but in some cases it makes sense or is necessary to generate everything dynamically. Let's have a look at the following code:

<?php
    echo '<html>
        <head>
        <title>Title of the site</title> '.
       '</head>';
    echo "<body>hello world<br></body></html>\n";
?>

The first echo command consists of two parts. The first three lines can be found between two single quotes. PHP recognizes that the command continues in the next line and does not end in the first line of the echo command. This way multiple lines can be treated as one command. Another way is to use a string operation as you can see at the end of line number 3 of the echo command. After the single quote, we use a point to tell PHP that the first string, which has just ended, has to be connected with the next string. In this case the second string is </head>. All components of the first echo command are passed to PHP in single quotes.

The second echo command contains the text we want to be displayed on the screen. This time we pass the text to echo using double quotes. Using single quotes or double quotes makes a significant difference: Single quotes are used to pass static text to PHP. Using double quotes allows you to use variables within the string. Knowing this difference is important because otherwise you might run into trouble. When executing the script you have just seen, the result will be a simple HTML document:

<html>
        <head>
        <title>Title of the site</title> 
        </head>
        <body>hello world<br></body>
</html>

The HTML is still not more than a simple "Hello World" application, but it is already HTML code.

3.1.2 Variables

Variables are a core component of almost every programming language available, and without variables it would be impossible to write useful applications. The idea behind variables is to have a language component that can have different values assigned to it. It is also possible to use variables as containers for storing data that is used in many different places in your application. Let's imagine an example where you want to display the same text on the screen twice:

<?php
    $text="hello world";
 
    echo '<html><head><title>Title of the site</title></head><body>';
    echo "$text<br>";
    echo "$text<br>";
    echo '</body></html>';
?>

First, you assign the string you want to be displayed on the screen to the variable called text. In the next step some HTML code is generated and the variable is printed on the screen twice. Keep in mind that we have to use double quotes instead of single quotes; otherwise, the result would be:

$text
$text

With single quotes, variables cannot be used within a string, so the result is not what you want it to be.

Figure 3.1 shows what comes out when you look at the result using Mozilla.

Figure 3.1Figure 3.1 A more sophisticated version of Hello World.

3.1.3 Adding Comments

Documentation is nearly as important as the code of a program. Nowadays only 10% of all costs of producing a software product are used for writing the source code. The remaining 90% are used for maintaining the product (this information is provided by the University of Vienna). To reduce the costs of maintaining a product and to reduce the time required to become familiar with the source code, it is essential to add comments to your programs. PHP provides some simple ways to add comments to a program:

<?php
    // this is a comment
    /* a C-style comment */
    echo 'hello world';
?>

In PHP comments can be added to the code as in C and C++. // tells the interpreter that the entire line should not be executed. /* */ is the old C style, which is also supported by PHP. C-style comments can be used to insert commands consisting of multiple lines:

<?php
    /*
     a C-style comment
     which is longer than just one line.
    */
?>

We recommend making heavy use of comments to make your code clearer and easier to understand. Especially if you are not the only one who will have to work with the code, comments will make your daily life much easier.

3.1.4 Executing PHP from the Command Line

In many cases it is useful to execute PHP code from the command line instead of executing the script by starting it using a Web browser.

Let's return to the three-liner called hello.php that we discussed at the beginning of this chapter:

<?php
    echo 'hello world<br>';
?>

To execute a script using a shell command, try the following:

[hs@athlon test]$ php ./hello.php
X-Powered-By: PHP/4.0.4pl1
Content-type: text/html
 
hello world<br>

As you can see, PHP produces more output than just "hello world". The additional information created by PHP defines which output has been created by PHP. In this case it is text/html. To make sure that the entire output is sent to standard output and not to standard error, we redirect all errors returned by PHP and see what comes out:

[hs@athlon test]$ php ./hello.php 2> /dev/null
X-Powered-By: PHP/4.0.4pl1
Content-type: text/html
 
hello world<br>

The result is still the same, and this shows that no errors have occurred.

PHP provides a lot of command-line parameters that can make daily life with the language much easier:

[hs@athlon test]$ php -h
Usage: php [-q] [-h] [-s] [-v] [-i] [-f <file>] | {<file> [args...]}
 -q       Quiet-mode. Suppress HTTP Header output.
 -s       Display colour syntax highlighted source.
 -f<file>    Parse <file>. Implies ´-q'
 -v       Version number
 -c<path>    Look for php.ini file in this directory
 -a       Run interactively
 -d foo[=bar]  Define INI entry foo with value 'bar'
 -e       Generate extended information for debugger/profiler
 -z<file>    Load Zend extension <file>.
 -l       Syntax check only (lint)
 -m       Show compiled in modules
 -i       PHP information
 -h       This help

As you can see, PHP provides a lot of options you can use from the command line directly. Many developers use only a Web browser to build and to debug PHP applications. Using PHP's command-line parameters can make life much easier; we strongly recommend making heavy use of these features.

One of the most important command-line flags is the -m flag, which you can use to ask PHP which modules have been compiled. This is extremely important if you have not compiled PHP yourself or if you no longer know which modules you added at compile time:

[hs@athlon test]$ php -m
Running PHP 4.0.4pl1
Zend Engine v1.0.4, Copyright (c) 1998-2000 Zend Technologies
 
[PHP Modules]
imap
ldap
mysql
pgsql
zlib
yp
xml
wddx
sysvshm
sysvsem
standard
sockets
session
posix
pcre
gettext
gd
ftp
dba
 
[Zend Modules]

As you can see, the standard PHP distribution included in Red Hat 7.1 supports a lot of modules. You will learn about many of these modules in this book, which will guide you through the details of these modules. One module you will have a very close look at is the pgsql module, which is responsible for interacting with PostgreSQL databases.

An important command-line flag of the PHP interpreter is the -i flag, which can be used to generate information about PHP itself. To generate the result, you can use the following:

[hs@athlon test]$ php -i > /tmp/phpinfo.html

The HTML file that has been generated is very long, so it is not included here.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus