A Brief Introduction to PHP:
Hypertext Preprocessor
by Phil Davis

PHP is a server-side, cross-platform, HTML-embedded scripting language. Currently there are over half a million domains running PHP and it is freely available for download online from www.php.net. Much of PHP’s syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly. PHP eliminates the need for numerous small cgi programs by allowing you to place simple scripts directly in your HTML files. It also makes it easier to manage large web sites by placing all components of a web page in a single html file.

For example, if you are creating an online catalog, you will most likely have a design template for all related catalog pages. Traditionally, this design is generated by hand in HTML and different data is presented within the template design. With PHP, one application can be used to generate all the pages required to display items from a database in the proper pages, in the right locations, and with the appropriate related content. This eliminates redundant page generation, simplifying maintenance. PHP also reduces the site down to a handful of template pages, with scripts that generate the rest of the site.

PHP is an excellent alternative to such similar programming solutions as Microsoft's proprietary scripting engine ASP and Allaire's rather expensive ColdFusion. As mentioned before, PHP is a cross-platform language. This doesn't stop with the core PHP code but can be extended to all of PHP's libraries and all code written in PHP. Neither ASP nor ColdFusion can make this claim. PHP has a large feature set which includes built-in support for numerous databases (including Access, LDAP, Oracle, and MSSQL), networking support, zip archiving ,and an excellent set of built-in functions. Furthermore, due in part to it being open source and freely available for download on the web, the language enjoys an active developing environment. Since the syntax structure borrows heavily from C, it is easy for even the novice programmer to learn the language. PHP is also the oldest HTML-embeded scripting language, giving it a head start on all the others.

If you are a content developer, you probably won’t want to learn PHP scripting by heart. But, it is nice to know how PHP can help you create more powerful web applications and user-friendly designs.

How PHP Works…

When you create a PHP application, you create PHP script files which are plain text files comprising a combination of standard HTML code and script commands. While web servers normally send HTML files directly to the client’s web browser in response to HTTP (HyperText Transfer Protocol) requests, the web server first processes the content of PHP scripts before sending output to clients. Within a PHP script, standard HTML code is sent directly to the browser, while script commands are executed locally on the web server. The script output can then be sent to the browser as standard HTML.

<HTML>

<HEAD><TITLE>My First PHP Script</TITLE></HEAD>

<BODY>

<? echo("Hello World!<P>"); ?>

</BODY>
</HTML>[ Run Script ]

 

Note the two <?...?> tags in the above text. This syntax indicates PHP commands that are interpreted by the server instead of being passed to the client. You may jump in and out of PHP mode in an HTML file like this all you want. This program is extremely simple and you really didn't need to use PHP to create a page like this. All it does is display "Hello World" using the ECHO command. With ECHO you can print out strings enclosed in quotes, variables, or a combination of both. At the end of the ECHO command you will see a semicolon (;). Almost every PHP command must end in a semicolon (;).

By clicking on the blue magnifying glass in the bottom right corner of the code window above you can view the code results in a separate browser window. If you view the source, you will see the following:

<HTML>

<HEAD><TITLE>My First PHP</TITLE></HEAD>

<BODY>

Hello World!

</BODY>
</HTML>

 

As you see, the scripting commands are not visible on the client side. This is good because it keeps the source code for the PHP protected. This means the original PHP code cannot be downloaded and copied without permission. So let's try something useful by generating a table of font colors generated on the fly. If you were to do this by hand it would take a very long time, with PHP it only takes a very few well placed lines of code.

<HTML>

<HEAD><TITLE>PHP Font Chart</TITLE></HEAD>

<BODY>

<TABLE>
<? 
for($iR = 0; $iR <= 255; $iR += 51) {
 for($iG = 0; $iG <= 255; $iG += 51) { 
?>
 <TR>
   <? for($iB = 0; $iB <= 255; $iB += 51) { ?>
    <TD>
     <FONT COLOR="<? printf("%02X%02X%02X", $iR, $iG, $iB); ?>">
      Font #<? printf("%02X%02X%02X", $iR, $iG, $iB);  ?>
     </FONT>
    </TD>

   <? } ?>
 </TR>
<? } } ?>

</TABLE>

</BODY>
</HTML>[ Run Script ]

 

The above simple program prints out "Netsafe colors" which are colors that display relatively similar in all browsers across all platforms. The program sets up an HTML page with three "for" loops, one for each of the RGB elements. The FOR loop is the most complex loop in PHP, it consists of three parts, or expressions:

 

FOR(expr1; expr2; expr3) statement

The first expression (expr1) is evaluated only once at the beginning of the loop. In the beginning of each loop, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statements are executed. If it evaluates to FALSE, the execution of the loop ends. At the end of each iteration, expr3 is evaluated. In our program we set expr1 in each of the loops to a variable ($iR, $iG, $iB) which holds a decimal number representing a piece of our Netsafe colors (0, 51, 102, 153, 204, or 255). In expr2 we compare our variable to see if it is greater than 255, if it is we exit the loop, if not we run the statements following the FOR loop and then evaluate expr3 which adds 51 to our variable using the "+=" operator. For example, in our first FOR loop we have "$iR += 51" this literally means take the current value of $iR, add 51 to it and then assign it back to $Ir. In addition to being more concise, it results in faster execution time.

The three loops together cycle through the 216 colors that will not dither in a web browser. Each time the second loop is run it prints a table row. Each time the third loop is run it prints a table element which includes a font tag with a PHP formatted print statement:

printf("%02X%02X%02X", $iR, $iG, $iB);

 

Printf allows us to output a formatted string consisting of our RGB variables. The first part of the printf statement is the format specification to use. The remaining comma delimited portions are variables, strings or numbers to print out using the format specification. Notice that the specification string repeats itself three times ("%02X"), once for each variable that we are outputting. The "%" marks the beginning of a format string. The next character is an optional padding specifier that says what character will be used for padding the results to the right string size. In our case we want all our hexadecimals padded with 0, hence the "0" in our format string.. The next number is a width specifier that says how many characters (minimum) this conversion should result in, in our case "2". Finally we have a type specifier that says what type the argument data should be treated as. In this case we want to convert our decimal numbers to hexadecimal. We use the "X" in the format string to do this.

Show Me More!

So now you are thinking that all this is great, but what you really want to do is print out a bunch of names from a database. This is much easier than it may sound at first. For our next example we will connect to a readily available Microsoft Access database. The database file is PHPTest.mdb and contains one table called "Contacts". The Contacts table contains three columns labeled UserID, FirstName, and LastName and looks something like this…

UserID FirstName LastName
1092 Lisa Vincent
2938 Pat Charles
9284 Christine Honeycutt
2837 Mike Vincent

 

The database requires a System DSN to be set up under the webserver’s ODBC connections. Your system administrator should be able to do this for you, but if you are developing on your local machine or you have permission to do it yourself on a development box, it is rather straightforward and just requires a few simple steps.

The following program will execute a SQL command against our Access database and print out the UserID and FirstName of all the contacts that have a LastName field that matches "Vincent"...

<HTML>

<HEAD><TITLE>My First PHP Database Connection</TITLE></HEAD>

<BODY>

<P>

<?
$cs = odbc_connect("PHPTest", "", "");
$res = odbc_exec($cs, "SELECT UserID, FirstName FROM Contacts WHERE LastName = 'Vincent'");

if ($res) 
   { 
    $nfields = odbc_num_fields($res); 
    echo("This is a list of  the Vincent's found in our database...<P>"); 

    echo("<TABLE>"); 
    echo( "\n<TR BGCOLOR=\"#E0FFFF\">"); 
    for($i= 1; $i <= $nfields; $i++ ) 
       { 
        echo("<TH>" . odbc_field_name($res, $i) . "</TH>"); 
       } 
    echo("</TR>"); 

    while(odbc_fetch_row($res))
       { 
        echo("<TR>");
        for($j = 1; $j <= $nfields; $j++) 
           {
            echo("<TD>" . odbc_result($res, $j) . "</TD>"); 
           } 
        echo("</TR>"); 
       }
    echo("</TABLE>");
   } 
else 
   { 
    echo("There are no Vincent's in our database!"); 
   } 
?> 

</BODY> 
</HTML>

 

Whatever you do don’t panic, its not nearly as bad as it may look. The majority of the lines are simple ECHO statements which we have seen before. Two of the lines are FOR loops and one line is a PRINTF which we have been over as well. This leaves an IF_THEN_ELSE statement which you are probably familiar with. The IF construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. Whatever is in the parenthesis after the IF is evaluated to its truth value. If it evaluates to TRUE, the next statement will be executed, and if it evaluates to FALSE - it'll ignore it. The ELSE found several lines below the IF extends our IF statement to execute a statement in case the expression in the IF statement evaluates to FALSE.

Now we get to the important bits. Notice the commands which start with ODBC? These are all ODBC specific commands which we use to interact with our database. The first command we execute is ODBC_CONNECT which we pass our System DSN name. ODBC_CONNECT returns an ODBC connection ID. The two empty quotes represent a USERNAME/PASSWORD combination which are not required for our database. Next we send the connection ID along with a SQL query to the database using ODBC_EXEC which returns a result identifier if the SQL command was executed successfully, otherwise a 0 (FALSE) will be returned. The result identifier is very important and we will need to send it to several of the other ODBC commands which we invoke. It basically represents the information that was returned from our query.

IF the SQL statement was executed successfully we then perform the statements under the IF statement, otherwise we print out "There are no Vincent’s in our database!" The first line inside the IF statement is ODBC_NUM_FIELDS which returns the number of fields contained in our SQL query. We use this information to loop through all the elements in the SQL query and print them out to a HTML table. But before we can loop through all the elements we must first retrieve the field names using ODBC_FIELD_NAME and print those as the table headers. We do this by looping through each of the fields and sending the SQL result identifier and field number as parameters to ODBC_FIELD_NAME, it returns to us the actual name of the field (i.e. "FirstName" and "UserID") Notice that we make the actual function call within the ECHO statement. We do this by appending the results of the call to the surrounding parameters of the echo statement with the DOT "." operator. You can use the DOT operator anywhere you need to append string information together.

The last two ODBC commands we have to examine are ODBC_FETCH_ROW and ODBC_RESULT. Each time ODBC_FETCH_ROW is called it proceeds on to the next row of our SQL results. The ODBC_FETCH_ROW command returns a TRUE if a row was retrieved, otherwise it returns a FALSE. The WHILE loop which the ODBC_FETCH_ROW is contained in looks at this TRUE/FALSE result and performs a loop if the results are TRUE, otherwise the WHILE loop quiets. Inside the WHILE loop we print out a table row and loop through all of the fields that need to be output. To retrieve a field to print we use ODBC_RESULT, passing it the result identifier and the number or name of the field we wish to retrieve.

So Now What?

So now that you have a taste for PHP, you will probably be looking for more information on it. The upcoming new edition of O'Reilly WebMaster's Guide will have a large section devoted to PHP and a full O’Reilly book will follow this. The authors are 5 of the PHP core development team (Andi Gutmans, Rasmus Lerdorf, Stig Bakken, Shane Caraveo and Zeev Suraski) . Support may be found online from sample code archives, function libraries and a PHP mailing list that receives close to 2500 messages per month!

Many more resources can be found online…


Back to Phil's homepage.