05 6191 ch03 11/25/03 11:59 AM Page 27

HOUR 3 A First Script

What You’ll Learn in This Hour: . How to create, upload, and run a PHP script . How to incorporate HTML and PHP in the same document . How to make your code clearer with comments

You installed and configured PHP in the last hour. It is now time to put it to the test. In this hour, you will create your first script and spend a little time analyzing its syn- tax. By the end of the hour, you should be ready to create documents that include both HTML and PHP.

Our First Script

Let’s jump right in with a PHP script. To begin, open your favorite . Like HTML documents, PHP files are made up of , so you can create them with any text editor, such as Notepad and HomeSite on Windows, Simple Text and BBEdit on Mac OS, or VI and on Unix operating systems. Most popular HTML editors provide at least some support for PHP.

Keith Edmunds maintains a handy list of PHP-friendly editors at Did you http://phpeditors.linuxbackup.co.uk. Know?

Type in the example in Listing 3.1 and save the file. We’ll name our file listing3.1.. 05 6191 ch03 11/25/03 11:59 AM Page 28

28 Hour 3

LISTING 3.1 A First PHP Script 1:

The code in Listing 3.1 causes information about our PHP installation to be out- put to the browser. The phpinfo() function is very useful for debugging scripts because of the contextual information it provides.

The extension to the PHP document is important because it tells the server to treat the file as PHP code and invoke the PHP engine. The default PHP extension for a PHP document is .php. This can be changed, however, by altering the server’s configuration. You saw how to do this in Hour 2, “Installing PHP.” System admin- istrators occasionally configure servers to work with non-default extensions, so some server setups might expect extensions such as .phtml or .php5. As you saw in the last hour, for example, Apache uses the AddType directive to determine how a file should be treated. AddType is usually found in Apache’s configuration file, httpd.conf:

AddType application/x-httpd-php .php

If you are not working directly on the machine that will be serving your PHP script, you will probably need to use an FTP client, such as WS_FTP for Windows or RBrowser Lite for MacOS, to upload your saved document to the server.

Watch For historical reasons, different operating systems use different character combina- Out! tions to denote the end of a line of text. You should save your PHP documents with the correct line breaks for the that runs your server. A document with the wrong line breaks for the operating system might be read as a single very long line of text by the PHP engine. This usually causes no problems, but the occa- sional bug can result. Most good text editors allow you to nominate your target oper- ating system.

After the document is in place, you should be able to access it via your browser. If all has gone well, you should see the script’s output. Figure 3.1 shows the output from the listing3.1.php script.

If PHP is not installed on your server or your file’s extension is not recognized, you might not see the output shown in Figure 3.1. In these cases, you might see the source code created in Listing 3.1, or you might be prompted to download the file! The effect of a misconfiguration depends your platform, server and browser. Figure 3.2 shows what happens to Internet Explorer when an unknown extension is encountered by Apache running PHP as a module on Linux. 05 6191 ch03 11/25/03 12:00 PM Page 29

A First Script 29

FIGURE 3.1 Success: The output from Listing 3.1.

FIGURE 3.2 Failure: The extension is not recognized.

If this happens, or you see the script’s source code in the browser window, first check the extension with which you saved your PHP script. If you are used to working with HTML files, for example, check that you have not saved your script with a . extension. If the file extension is as it should be, you might need to check that PHP has been installed properly and that your server is configured to work with the extension you have used for your script. You can read more about installing and configuring PHP in Hour 2. To produce the output shown in Figure 3.2, we removed the AddType directive from Apache’s configuration file. 05 6191 ch03 11/25/03 12:00 PM Page 30

30 Hour 3

By the Configuration problems vary between servers and platforms. Omitting the Action Way directive from Apache’s httpd.conf file when running PHP as a CGI results in errors, for example. If you encounter unexpected behavior, you should refer to the installation instruc- tions for your server. You can find complete instructions for setting up PHP with most servers at http://www.php.net/installation.

Now that you have uploaded and tested your script, you can take a look at the code in a little more detail.

Beginning and Ending a Block of PHP Statements When writing PHP, you need to inform the PHP engine that you want it to exe- cute your commands. If you don’t do this, the code you write will be mistaken for HTML and will be output to the browser. You can do this with special tags that mark the beginning and end of PHP code blocks. Table 3.1 lists four such PHP delimiter tags.

TABLE 3.1 PHP Start and End Tags Tag Style Start Tag End Tag Standard tags Short tags ASP tags <% %> Script tags

Of the tags in Table 3.1, only the standard and the script tags can be guaranteed to work on any configuration. The short and ASP style tags must be explicitly enabled in your php.ini, which you examined in Hour 2.

To activate recognition for short tags, you must make sure that the short_open_tag switch is set to “On” in php.ini, like so:

short_open_tag = On;

Short tags are enabled by default, so you need to edit php.ini only if you want to disable these.

To activate recognition for the ASP tags, you must enable the asp_tags setting, like so:

asp_tags = On; 05 6191 ch03 11/25/03 12:00 PM Page 31

A First Script 31

After you have edited php.ini, you should be able to choose from any of the four styles for use in your scripts. Having said this, it is not advisable to use anything but the standard tags. It is the officially supported syntax, it works well with XML, and it works in any PHP context. Furthermore, there is no guarantee that short tags will be supported forever.

The character sequence Out!

This syntax clashes with the PHP short tag. Used as part of an XML or XHTML docu- ment, PHP short tags could confuse an XML validator, the PHP engine, or both. Disable short tags if you intend to use PHP in an XML context.

You should also avoid short or ASP tags if you want your script to be portable. Third-party servers might not be configured to support these tags.

Let’s run through some of the ways in which you can legally write the code in Listing 3.1. You could use any of the four PHP start and end tags that you have seen:

<% phpinfo(); %>

Single lines of code in PHP also can be presented on the same line as the PHP start and end tags, like so:

Now that we have proved to ourselves that PHP is working, let’s move on and write some more code. 05 6191 ch03 11/25/03 12:00 PM Page 32

32 Hour 3

The print() Function In Listing 3.1 we used the phpinfo() function. In Listing 3.2 we change our script so that we print something to the browser for ourselves.

LISTING 3.2 Printing a Message 1:

print() is a language construct that outputs data. Although it is not a function, it behaves like one: It accepts a collection of characters, known as a string. Strings must be enclosed by quotation marks, either single or double. The string passed to print() is then output, usually to the browser or command line.

By the Similar to the print() statement is echo(), which behaves in the same way (except Way that it does not return a value). For most examples in this book, you could replace all uses of print() with echo() without any noticeable effect.

By the Function calls generally require parentheses after their names, regardless of whether Way they demand arguments. print() is, strictly speaking, a language construct rather than a function and does not demand the use of parentheses. As parentheses are omitted by convention, we will usually omit them in our examples.

We ended our only line of code in Listing 3.2 with a semicolon. The semicolon informs the PHP engine that we have completed a statement.

A statement represents an instruction to the PHP engine. Broadly, it is to PHP what a sentence is to written or spoken English. A sentence should end with a period; a statement should usually end with a semicolon. Exceptions to this include statements that enclose other statements and statements that end a block of code. In most cases, however, failure to end a statement with a semicolon con- fuses the PHP engine and results in an error being reported at the following line in the script.

Because the statement in Listing 3.3 is the final one in that block of code, the semicolon is optional. 05 6191 ch03 11/25/03 12:00 PM Page 33

A First Script 33

Combining HTML and PHP

The code in Listing 3.1 and Listing 3.2 is pure PHP. You can incorporate this into an HTML document simply by adding HTML outside the PHP start and end tags, as shown in Listing 3.3.

LISTING 3.3 A PHP Script Including HTML 1: 4: 5: 6: Listing 3.2 A PHP Script Including HTML 7: 8: 9:

10: 13:
14: 15:

As new devices access the Web running new browsers on ever more platforms, stan- By the dards are becoming increasingly important. Where possible, the output from code Way examples in this book now conform to Extensible Hypertext Markup Language (XHTML) standards. XHTML is an XML-based version of HTML that can be parsed and validated. Because of this, it is more accessible to lightweight browsers running on small memory devices. XHTML also helps to promote genuinely cross-browser mark-up. You can read more about XHTML at http://www.w3.org/TR/xhtml1/. Notice that Listing 3.3 starts with a complex-looking element. This is known as the DOCTYPE declaration, and it declares the XHTML version to which the document con- forms.

As you can see, incorporating HTML into a PHP document is simply a matter of typing in the code. The PHP engine ignores everything outside PHP open and close tags. If you were to view Listing 3.3 with a browser, as shown in Figure 3.3, you would see the string hello world in bold. If you were to view the docu- ment source, as shown in Figure 3.4, the listing would look like a normal HTML document. 05 6191 ch03 11/25/03 12:00 PM Page 34

34 Hour 3

FIGURE 3.3 The output of Listing 3.2 as viewed in a browser.

FIGURE 3.4 The output of Listing 3.2 as HTML source code.

You can include as many blocks of PHP code as you need in a single document, interspersing them with HTML as required. Although you can have multiple blocks of code in a single document, they combine to form a single script. Any variables defined in the first block usually are available to subsequent blocks. 05 6191 ch03 11/25/03 12:00 PM Page 35

A First Script 35

Adding Comments to PHP Code

Code that seems clear at the time of writing can resemble a hopeless tangle when you try to amend it six months later. Adding comments to your code as you write can save you time later and help other more easily work with your code.

A comment is text in a script that is ignored by the PHP engine. Comments can be used to make code more readable or to annotate a script.

Single-line comments begin with two forward slashes (//) or a single hash sign (#). All text from either of these marks until either the end of the line or the PHP close tag is ignored. Here’s an example:

// this is a comment # this is another comment

Multiline comments begin with a forward slash followed by an asterisk (/*) and end with an asterisk followed by a forward slash (*/), as in the following:

/* this is a comment none of this will be parsed by the PHP engine */

The PHP Extension and Application Repository (PEAR) provides a growing collection Did you of libraries and scripts for extending PHP’s functionality. It includes a package called Know? phpDocumentor, which can convert your inline comments into hyperlinked documen- tation. This is extremely useful for maintaining large projects. You can read more about PHPDocumentor at http://phpdocu.sourceforge.net. We cover PEAR and phpDocumentor in more detail in Hour 23, “PEAR: Reusable Components to Extend the Power of PHP.”

Summary

You should now have the tools at your disposal to run a simple PHP script on a properly configured server.

In this hour, you created your first PHP script. You also learned how to use a text editor to create and name a PHP document. You examined four sets of tags that you can use to begin and end blocks of PHP code, and you learned how to use 05 6191 ch03 11/25/03 12:00 PM Page 36

36 Hour 3

print() to send data to the browser. Then you brought HTML and PHP together into the same script. Finally, you learned about comments and how to add them to PHP documents.

In the next hour, you will use these skills to test some of the fundamental build- ing blocks of the PHP language, including variables, data types, and operators.

Q&A Q Which are the best start and end tags to use?

A It is largely a matter of preference. For the sake of portability, the standard tags () are probably the safest choice. Short tags are enabled by default and have the virtue of brevity, but to promote portability, it might be safest to avoid them.

Q Which editors should I avoid when creating PHP code?

A Do not use word processors that format text for printing (such as Word or OpenOffice). Even if you save files created using this type of editor in plain text format, hidden characters can creep into your code.

Q When should I comment my code?

A This is a matter of preference once again. Some short scripts will be self- explanatory to you, even after a long interval. For scripts of any length or complexity, you should comment your code. This will save you time and frustration in the long run.

Workshop

Quiz 1. Can a user read the source code of PHP script you have successfully installed? 2. What do the standard PHP delimiter tags look like? 3. What do the ASP PHP delimiter tags look like? 4. What do the script PHP delimiter tags look like? 5. What syntax would you use to output a string to the browser? 05 6191 ch03 11/25/03 12:00 PM Page 37

A First Script 37

Answers 1. No, the user sees only the output of your script.

2. .....

3. ....<% ....// your code here ....%>.

4. .....

5. We would usually use print() to write to the browser, although we could use echo() with the same results.

Exercise 1. Familiarize yourself with the process of creating, uploading, and running PHP scripts. In particular, create your own “hello world” script. Add HTML code to it and additional blocks of PHP. Experiment with the various PHP delimiter tags. Which ones are enabled in your configuration? Take a look at your php.ini file to confirm your findings, and don’t forget to add some comments to your code.