Incorporating PHP Within HTML

By default, PHP documents end with the extension .php. When a web server encounters this extension in a requested file, it automatically passes it to the PHP processor. Of course, web servers are highly configurable, and some web developers choose to force files ending with .htm or .html to also get parsed by the PHP processor, usually because they want to hide the fact that they are using PHP.

Your PHP program is responsible for passing back a clean file suitable for display in a web browser. At its very simplest, a PHP document will output only HTML. To prove this, you can take any normal HTML document, such as an index.html file, and save it as index.php; it will display identically to the original.

To trigger the PHP commands, you need to learn a new tag. The first part is:

<?php

The first thing you may notice is that the tag has not been closed. This is because entire sections of PHP can be placed inside this tag, and they finish only when the closing part, which looks like this, is encountered:

?>

A small PHP “Hello World” program might look like Example 3-1.

The way you use this tag is quite flexible. Some programmers open the tag at the start of a document and close it right at the end, outputting any HTML directly from PHP commands.

Others, however, choose to insert only the smallest possible fragments of PHP within these tags wherever dynamic scripting is required, leaving the rest of the document in standard HTML.

The latter type of programmer generally argues that their style of coding results in faster code, while the former say that the speed increase is so minimal that it doesn’t justify the additional complexity of dropping in and out of PHP many times in a single document.

As you learn more, you will surely discover your preferred style of PHP development, but for the sake of making the examples in this book easier to follow, I have adopted the approach of keeping the number of transfers between PHP and HTML to a minimum—generally only once or twice in a document.

By the way, a slight variation to the PHP syntax exists. If you browse the Internet for PHP examples, you may also encounter code where the opening and closing syntax used is like this:

<?
echo "Hello world";
?>

Although it’s not as obvious that the PHP parser is being called, this is a valid, alternative syntax that also usually works. However, it should be discouraged, as it is incompatible with XML and its use is now deprecated (meaning that it is no longer recommended and that support could be removed in future versions).

Note

If you have only PHP code in a file, you may omit the closing ?>. This can be a good practice, as it will ensure you have no excess whitespace leaking from your PHP files (especially important when writing object-oriented code).