Create a Simple PHP Program

Begin by following these steps to write a Web page that will appear in just about any browser you can find.

  1. Open Notepad or any handy text editor and enter the following HTML code:

        <title>Web Page</title>
        The text here displays in my browser window
  2. Save the file with any name you choose and an extension of .htm (simple01. htm, for example).

  3. Open the file in your browser.

  4. Based on the installation and setup, you should be able to upload the file to the appropriate server area (if you're working on the machine running the Web server, simply copy the file into a folder served by your Web server software). Bring the file up again from the Web server folder by using the HTTP address for the local host. The result should look exactly the same.

  5. Now replace the line beginning with "The text..." with the following lines:

    The text here displays the date as a result of PHP5 processing: Today is
    $todaysdate = date("m",time()) . "-" . date("d",time()) . "-"
    date("Y", time());
    echo $todaysdate;
  6. Save the file, upload it if you need to, and refresh it in your browser. Anything happen? Probably not, unless you changed the file extension from . htm to . php. You see, in order for the Web server to refer the file to the PHP5 processing engine, it first needs to be aware that the file is a PHP file, and it learns this from the file extension. Second, assuming the file has the proper extension, the PHP5 processing engine picks out the sections of PHP code to process by parsing the file, looking for the PHP delimiters (<?php and ?>), and then executing the PHP code. Parsing means the processing engine reads the individual commands and checks for syntax errors (a very common error you'll find in your PHP code is the parse error). Executing simply means the processing engine actually runs the code and does the processing.

  7. Change the file extension to . php and bring up the file from the server. This time the code should execute and you should see the date at the end of the line of text.

Explore Some Details

There are many commands, keywords, statements, language constructs, and functions in the PHP programming language, just like any other programming language. The PHP processing engine looks for these during parsing, and if the syntax is correct, it processes them and returns the result of that processing. When you're running a Web application, the results should be compatible with HTML or scripting languages in the Web page in which they appear, so often the results of processing include HTML tags.

The echo function is actually not a function but a language construct, meaning that it doesn't need parentheses to contain arguments, it doesn't return a value (but it does do what it's supposed to do, namely send a string value to the browser), and it has a few other restrictions that functions don't have. echo is not the only language construct in PHP; unset is another example. At this point, the most important thing for you to know is that echo sends a string back to the browser; in later chapters you'll find out more about the distinctions between languages constructs and functions.

So echo sends string data to the user. The data can include HTML code, but if none is present the user will still see the text in his browser (the browser treats it like reading a text file, and "fills in" the HTML to make it appear normally). In this code from the simple example, echo sends the string data you composed for today's date and placed in the $todaysdate variable:

echo $todaysdate;

The date() function is built in to PHP, meaning that you don't have to write or copy the function into your PHP5 program; it's simply there for you to use at any time. It's written in the same way as functions in most languages. It starts with the name of the function followed by parentheses, and inside the parentheses are arguments—the values, expressions, or more functions that resolve to a value which is then used by the date() function to produce the final answer. Take a look at this line from the example program:

$todaysdate = date("m",time()) . "-" . date("d",time()) ."-".

The first argument is "m", signifying to the date() function that you want to know the month. The second argument uses the time() function, which gets the current time. The date() function processes the current time and extracts the month as a two-character value. You can use the date() function again to get the day and year from the time() function.

How PHP Code Works

As the preceding example illustrates, the basic requirements for a running PHP program within a Web page are as follows:

  • Some type of Web page with which the user can interact

  • A file extension of . php

  • Recognizable PHP delimiters

  • PHP code that is syntactically correct

Let's look at each of these in more detail.

Web Pages (User Interface)

It's important to have a firm grasp on how Web pages perform as well as how PHP5 works, because the rendered page is all that the end user ever sees of your PHP programs. By the way, although the rendered output usually is referred to as HTML, HTML is giving way to XHTML, and browsers are becoming capable of processing other, similar output, such as XML with XSLT. Although this book uses HTML to refer to the Web server's output, it also means other languages that browsers can render.

You can write PHP programs such that the PHP5 code is embedded in the HTML directly, or you can write your programs so that the HTML is essentially referenced from your PHP5 code as needed. Either way, all output to the end user should be HTML.

Why? Try opening the . php file as a file instead of as a Web page (in your browser, choose File⇨Open and locate the file on your hard drive). You won't see the PHP code in your browser (the browser ignores the PHP delimiters and what's between them) but if you choose View⇨Source, you see the unprocessed PHP code. That's because no Web server or PHP processing engine touched the file before your browser got it.

File Extensions

If you've built Web pages before, you're probably familiar with the . htm and . html filename extensions, and perhaps . shtml as well. These extensions indicate to the browser the file type being opened. The Web server is also aware of these extensions, and if it sees a .php file, it refers that file to the PHP engine for processing. The requirement for a filename extension of .php doesn't come from PHP5, but is the default for most from Web servers for PHP files.

It is possible to configure your Web server to send files with other extensions (such as . htm and . html) to the PHP processing engine. If you make this configuration change, your ordinary HTML Web pages will be processed through the PHP engine (in addition to all your PHP-coded Web pages), although ordinary HTML files won't change as a result (and this adds a bit of overhead). Because the files sent to the users will end with . htm or . html instead of .php, it won't be evident to them that PHP was being used for back-end processing. Whether to add these extensions is your choice, but it's recommended if you want to keep people from knowing that you're using PHP to process your Web application.

PHP Delimiters

Delimiters are used in many types of code to indicate code blocks, data, and so on. They are special characters that tell the parsing program where the data starts and stops. You've probably heard of comma-delimited text, in which case the delimiters are commas. Between one comma and the next, the program or engine parsing the data stream knows it should find data of the appropriate type.

The same concept applies to PHP code embedded in a Web page. The standard delimiters for PHP5 are <?php and ?>. You could use <? and ?>, but <?php and ?> are preferred—and specified by the PHP Extension and Application Repository (PEAR), a very good source of standard PHP code.

Like other settings in PHP5, you can adjust or expand the delimiters that the PHP processing engine will recognize by making changes to the configuration file. For example, you can make PHP5 recognize <% and %> as delimiters. These are called the ASP delimiters, referring to the delimiters commonly used when writing ASP embedded in Web pages. (ASP—Microsoft's Active Server Pages—is similar to PHP.)

You can also delimit PHP code using the HTML script tags, as in this example:

<script language="PHP">PHP code goes here</script>

"Correct" PHP

Like any programming language, PHP code must be written correctly if it is to run. When you run it from the Web server and it goes through the processing engine, any mistakes in your code generates an error that's displayed to you.

So syntactically correct PHP is required. But writing a program that is syntactically correct (and runs without errors) does not guarantee that your program will produce the "right" answer, because there may be logic errors in your code.

The code in your simple PHP program runs just fine, by the way.

Common Code Markers

PHP uses several characters to mark the end of lines and delimit code blocks. Notice that the two lines of code in the program both end with a semicolon (;), as shown in the echo statement:

$todaysdate = date("m",time()) . "-" . date("d",time( )) . "-" .
date("Y", time());
echo $todaysdate;

In PHP code:

  • Code statements end with a semicolon (;).

  • Code blocks are enclosed in curly braces ({}).

  • Comments in code begin with // for a single line, or begin with /* and end with */ to comment multiple lines.

Here's how these things look in a block of pseudo code (fake code used for outlining processing in PHP or illustrating a point):

//Put an echo statement here
echo "here's a bit of pseudo-code";
if ($varl == $var2) {
    //do something
    /* here's a multi-line comment
    do something
    do something else

It's important to remember these requirements, because the processing engine will generate an error and display a parse error when you forget. Folks who have already programmed Visual Basic or ASP are probably the most likely to forget, because semicolons and curly braces are not required in those programs, and the apostrophe (not the //) marks comments.

How Online PHP Programs Run

Unlike desktop applications, which run on your local system when their . exe file is activated, online PHP programs run when a request is made to the Web server. The request tries to get the Web server to retrieve and send the file requested, but before the response is composed, the PHP engine has a chance to process the PHP code in the file.

An important fact that often goes unsaid: Only a single PHP file can run at a given time (because only one file can be requested at a time from the server), and that means that even though you may have many PHP files on the Web server, each must function as its own little program. You can bring in other PHP files by using the include or require constructs (you'll see how to do this later), but doing so is merely like dynamically copying in all the code in those external files and still running a single file as a program. This is not some huge limitation, but it's worth mentioning, because all data and variables are lost each time the single page is processed and the HTTP request is fulfilled. There is a way to preserve data between page requests (using sessions) but the concept of "one file, one program" should be clear.

Any program that interacts with a server can be labeled a client program, and any program that provides services for client programs can be labeled a server. In fact, some programs operate as both client and server. In general use, however, programs such as browsers, FTP programs, and e-mail programs are clients, and make a connection to a server to perform most of their functions. The servers they typically connect to are Web servers, FTP servers, and mail servers.

The client-server relationship is important to PHP because all PHP code runs on the server, whereas the HTML and/or JavaScript code within Web pages is passed untouched back to the client for processing. Technically, you could send PHP code untouched back to the browser for processing there, but because most folks have no means of processing PHP code on their browser, it wouldn't work. One big advantage of the fact that PHP code is processed on the server is that, unlike JavaScript, the end user never has a chance to see your source code.