Skip to main content

skip to main content

developerWorks  >  Web development  >

PHP by example, Part I

Effortless Webzine authoring and delivery

developerWorks
Document options

Document options requiring JavaScript are not displayed


Rate this page

Help us improve this content


Level: Introductory

Erik Zoltan (erik@zoltan.org), Senior Information Specialist, EDS

12 Dec 2000

As a language for building dynamic Web pages, PHP offers a implified method for constructing complex and powerful Web-related programs.Step by step, Erik demonstrates the fundamental principles of PHP in an original, real-world Web site example. Part 1 of this two-part series offers the basics of PHP and features a Webzine that includes an author's page where content providers can enter the text of articles, as well as a front end for presenting this content to the world.

If you're new to PHP, you might be pleasantly surprised by how easy it is in practice. My intention is for you to come away with a good feel for what it's like to work in PHP; after that, you can decide whether or not it's right for you.

Hands-on PHP

Part 1 of this two-part series explains how the application works (it doesn't cover the installation of PHP on your system). You'll have a chance to try out the main index page, and then take a peek under the hood to see how some of the components work. If this only whets your appetite, then be sure to check out Part 2, which goes into more detail about the rest of the main index page. (Part 2 also discusses the authoring component with a few coding examples. You can download the source code and try out your own ideas.)

If you know HTML and are familiar with any C-like language (especially Perl), then you should have no problem comprehending the following examples. Even if you haven't used a C-like language very much, you might still be able to follow the examples. But you really do need to know the rudiments of HTML.

The sample PHP application is a reader-generated Webzine with a simple delivery module (less than 3K of code). This module shows a list of topics. Under each topic heading is a series of article summaries in reverse chronological order. The user can read the full article by clicking on the title. There's also a slightly more involved authoring module (about 8K of code) that lets any reader become an author and submit his or her own content. Authors must select a category and enter an article title, a brief synopsis, and the full text of the story. Optionally, you can enter the URL of an image file and click on a "Preview" button to verify that you got it right. The author's input is validated -- it's even put through a security check that will guard against risky or malicious HTML coding practices by converting all but a few safe tags into an inactive format. For example, the string <applet would become <applet. This conversion effectively disables the tag.



Back to top


A special PHP technique

Before I get into the actual Webzine code, let's start with a simple example that nicely illustrates the character of PHP. The syntax of PHP allows you to intermix HTML and PHP statements at will. This means that the HTML statements can appear inside the context of loops, if/else statements, functions, and so on. I do this in the Webzine program, but the following code sample boils it down in a simpler way.

Suppose we have the two arrays, $names and $days, containing information about the months of the year, so $days[0] = 31 and $names[0] = "January", $days[1] equals 28 and $names[1] equals "February", and so on. Here's a technique to create a table of day and month names:


Listing 1: Creating a table of day and month names

<table border="2">
<tr><th>Name</th><th>Days</th></tr>
<?php
   for($i=0; $i<12; $i++) { // Start of loop.
?>
<tr><td><?php
 echo($names[$i]) 
?></td>
    <td><?php
 echo($days[$i]) 
?></td></tr>
<?php
   } // End of for loop.
?>
</table>    

For clarity, the PHP statements above are in red; the HTML statements are in black. Note that the special tag <?php switches from HTML into PHP, and ?> switches back to HTML.

The important thing to note is that you can switch into PHP, start a for loop (or if/else, or switch, or whatever), then pop back into HTML and now the HTML commands you're entering will be part of the looping structure so they repeat along with the loop. You can go into and out of PHP mode as necessary (to issue echo statements that output variables into the Web page as I've done above, for example). Then, when you pop back into PHP and put an ending curly brace, the loop is complete, just as you'd expect.

Here's what the actual table would look like:

NameDays
January31
February28
March31
April30
May31
June30
July31
August31
September30
October31
November30
December31

If this behavior seems confusing, just think of it in the following way: The PHP interpreter will replace each line in HTML mode with an echo statement to put that line into the output stream. If that echo statement occurs in an if/else structure, it will be conditional. If it occurs within a loop (as above), then it repeats.



Back to top


Application overview

The Webzine driver, index.php3, has three major components (see here for a complete listing of the code for the driver): subject menu, story list, and full story presentation. There is also some default text that appears if the reader selects a topic that doesn't have any stories. The authoring page (view listing) is more complex. It contains a form to accept user input, a feedback message to inform the author of problems that need correcting, and a confirmation message to show the author what they submitted. It also knows how to validate the story submitted, make changes to ensure that it doesn't contain any unauthorized HTML, save it in a story file, and update the appropriate menu files that go with the story.

This application has three kinds of data files: Category.txt contains a simple list of the topics where the organization of stories occurs. Each topic associates with a topic menu file. The first topic must be "Main," and associates with a topic menu file Main.txt. If the second topic is "The Arts," then it associates with a topic menu file called TheArts.txt. The menu files contain information about each story on a separate line: a story number, title, category, brief synopsis and, optionally, an image URL. Finally, the story file contains the actual body text of one story. The file s1.txt would contain the first submitted story, s2.txt the second, and so on. If you know the number of a story (say number 26), its filename is easy to determine (s26.txt).



Back to top


Try it out!

Before you look at this application in detail, try it out.

Try the Webzine Driver. It presents you with a list of subjects on the left, and a list of stories on the right. You can select a topic, or "Main" to see all of the stories. A list of the most recent stories appears first, and images display for the first couple of stories that have images. When you click on the title of a story, it takes you to a page featuring the full text of that story.

Try the Authoring Page (or you can try it from within the Webzine itself). It presents you with a form that allows you to submit a story. Use common sense and good taste when submitting content to the Webzine. If you type something the program doesn't like, it will give you an error message. Upon acceptance of your story, you can return to the Webzine to see how it appears to the reader.

Now that you've tried out the application, continue reading to learn about its creation.



Back to top


Webzine driver

Passing parameters

$topic = "TradeShow";
$story = 33;

If you omit the parameters, the $topic and $story variables will simply not exist. You can test for them explicitly or rely on PHP to return a default empty value when you reference them.

Note: If this feature doesn't seem to be working on your system, look at php.ini and make sure that register_globals = On.

Web page title

Let's start by looking at a common technique in many PHP applications: placing certain kinds of information in variable assignment statements at the top of the program. This allows for ease of maintenance and updating later on.


Listing 2: Variable assignment

<?php
   $title = "PHP Demo Webzine"; 
  $slogan = "Illustrating the coolness of PHP since September 2000";
?>
<html>
 <head>
  <title><?php echo($title) ?></title>
 </head>
 <body>
  <h1><?php echo($title) ?></h1>
  <p><i><?php echo($slogan) ?></i></p>

Again, note the PHP boundary tags: <?php to take you out of HTML mode into PHP mode, and ?> to switch back into HTML mode. You can switch back and forth as many times as you like. Some things are just easier to do in HTML mode, and others are easier in PHP mode. All you're doing is defining two variables at the top of the program and then slipping into HTML mode. Whenever we need to use one of the variables, you pop back into PHP mode and issue an echo statement to write the variable's value directly into the Web page text.

Category menu

You'll get three topic menu files: Main.txt, Politics.txt and Technology.txt. The driver will appear as follows upon selection of the "Main" topic:

Main 
Politics
Technology

<table border="1">
 <tr><td bgcolor="pink"><center>
  <b> Main </b></center></td></tr>
 <tr><td bgcolor="silver"><center>
  <b> 
   <a href="index.php3?topic=Politics">Politics</a>   </b></center></td></tr>
 <tr><td bgcolor="silver"><center>
  <b>
    <a href="index.php3?topic=Technology">Technology</a>   </b></center></td></tr>
</table>

$cats
<?php
   $cats = file("category.txt"); 
   $elems = count($cats);
?>

The file function just copies the file into an array. So $cats[0] will equal "Main," $cats[1] equals "Politics" and $cats[2] equals "Technology". The file function makes it a snap to import a short ASCII text file, but don't use it on very large files. The count function counts the number of elements in an array, so you would expect $elems to equal 3 in the example.

Here's how to create the above HTML table from that array:


Listing 3: Creating the HTML table

<table border="1">
<?php
   for ($i=0; $i<$elems; $i++) {
      $item = trim($cats[$i]);
      $ifile = ereg_replace(" ","",$item);
      $color = ($ifile == $topic) ? "pink" : "silver";
      $url = "index.php3?topic=$ifile";
      $anchor = " " . ($item != $topic ? "<a href=\"$url\">$item</a>" : "$item") . " ";
      echo(" <tr><td bgcolor=\"$color\"><center><b>$anchor</b></center></td></tr>\n");
   }
?>
</table>

<table border="1">

<?php

for
   for ($i=0; $i<$elems; $i++) {

trimfile
      $item = trim($cats[$i]);

$item$ifile
      $ifile = ereg_replace(" ","",$item);

$color?:test?truevalue:falsevalue$color
      $color = ($ifile == $topic) ? "pink" : "silver";

index.php?topic=Politics$ifile$ifile
      $url = "index.php3?topic=$ifile";

?:<a href="index.php?topic=Politics>Politics</a>Politics
      $anchor = " " . ($item != $topic ? "<a href=\"$url\">$item</a>" : "$item") . " ";

echo\"$color$anchor
      echo(" <tr><td bgcolor=\"$color\"><center><b>$anchor</b></center></td></tr>\n");

for
   }

?>

</table>

And that's it!

Story presentation

$story
      $storyfile = fopen("s$story.txt","r");
      fpassthru($storyfile);

In the above example, the fopen function opens a file, returning a handle to the file that is then placed in the variable $storyfile by the assignment operator. The fpassthru function copies the contents of the file to the current output device (the output HTML file), and automatically closes the file for you.



Back to top


What's next

Part 1 of this article presents the first part of a simple PHP Webzine application. I've covered a few small code examples in detail. (This part of the application is only 2K worth of code, so there weren't many large code examples to choose from!) This should give you a good taste of the power of PHP, but there's a lot more to come.

Part 2 is about the same length as Part 1. I'll complete the discussion of the delivery module by showing how presentation of the menu of stories appears to the reader. I'll then cover the authoring module that permits authors to submit stories. Although the authoring module is a lot larger, we will not cover it in as much detail: Only the interesting concepts that are different from the delivery module need an explanation.



Resources

  • Index.php3 provides a complete listing of the Webzine driver.

  • Author.php3 provides a complete listing of the authoring page described in the application overview.

  • PHP.net is the official home page of the PHP language. Here you can download the latest version of PHP for free, and check out what's going on in the development of PHP. There is a FAQ, a manual, and numerous other resources.

  • PHPbuilder.com is geared toward developers, containing numerous articles and code samples, job postings, and links to PHP resources.

  • Webmonkey's PHP Section contains a number of articles on PHP starting out at the introductory level.


About the author

Photo of Erik Zoltan

Erik Zoltan has been writing code professionally since 1990. He's a full-time telecommuter living in Leominster, Massachusetts. You can e-mail him at erik@zoltan.org or view his home page at www.zoltan.org. Erik drives a 1996 Saturn painted in Vincent Van Gogh's The Starry Night.




Rate this page


Please take a moment to complete this form to help us better serve you.



 


 


Not
useful
Extremely
useful
 


Share this....

digg Digg this story del.icio.us del.icio.us Slashdot Slashdot it!



Back to top