PHP Essentials

Articles > Webmaster > PHP Essentials

Many articles on this site refer to something called PHP — but what exactly is PHP?

PHP stands for PHP: Hypertext Preprocesor. Notice that the first letter of the acronym itself shows up as the first word in the expanded phrase. This is an example of geek humor.1 PHP files look like HTML, except that every now and then you see <?php some stuff ?>. And when I say 'you' I mean you, the web developer. Clients browsing the site will never see the <?php ... ?> because the web server will replace it with the results of executing some stuff.

Why You Should Care

PHP is powerful. You can use it for everything from hit counters to online stores. And, because everything happens on the web server, you never need to worry about browser incompatibility.

The Downside

Unfortunately, PHP is also complicated, even more complicated than HTML (but probably less complicated than CSS). It is also powerful, and if you don't know what you are doing you can crash the web server. For this reason I suggest that you venture into php cautiously, and always test your code on a local server2 before publishing to your real server.

Having said that, I do suggest that you venture into PHP! Don't be afraid — just move carefully. Writing a piece of PHP from scratch is hard, but finding an example on the web and modifying it to do what you want fairly straightforward.

An Example

Let's start out with a fairly simple example of PHP, a folder that lists its contents:

<html>
  <head><title>My Sites</title></head>
  <body>
  <?php

  /* get all files and folders */
  $files = glob("*");

  /* print each one */
  foreach ($files as $file)
    printItem($file);

  function printItem($x) {
    /* add a '/' to directories */
    if (is_dir($x))
      $x = "$x/";
  
    /* print the item */
    echo "<a href=\"$x\">$x</a><br />\n";
  }
  ?>
  </body>
</html>

Let's examine this piece by piece:

<html>
  <head><title>My Sites</title></head>
  <body>

  </body>
</html>

The HTML code is simply passed to the web browser. Here we have the basic declarations required for a web page.

  <?php
  ?>

The PHP script begins with <?php and ends with ?>. Everything between these tokens is executed on the server instead of being passed to the web browser.

  /* get all files and folders */
  $files = glob("*");

A comment in PHP begins with /* and ends with */. This is also, incidentally, how you declare comments in Cascading Stylesheet (CSS) files.3 A variable in PHP begins with a $. Variables are temporary placeholders that you can store things in. Four kinds of things, in fact: numbers, strings (sequences of characters), arrays, and objects. A function in PHP is a word followed by a pair of parenthesis (), and whatever goes inside the parenthesis are called the arguments to the function.

In this case we are calling the glob function.4 This function returns an array of all pathnames that match its argument (i.e., "*.html" would return all files ending in .html). Because we just passed "*" the function will return all files and folders in the current folder.

  /* print each one */
  foreach ($files as $file)
    printItem($file);

The foreach keyword tells the server to perform the following statement (printItem($file) in this case) once for every item in the first variable, and to store the item in the second variable before performing the statement. printItem() is another function, which we call with the argument $file.

Note that glob() was a built-in function, but printItem() is not — it's just a name that we made up. So the next thing that we need to do is define the function.

  function printItem($x) {

  }

A function declaration is the keyword "function" followed by a word, followed by a list of parameters in parenthesis. When the function is called, the values passed as arguments get stored iin the parameter variables and then the statements within the curly braces {} get executed.

    /* add a '/' to directories */
    if (is_dir($x))
      $x = "$x/";

The first thing our function does is call another function, is_dir(), which returns true if the argument passed is the name of a directory5 and false otherwise. The if keyword tells the server to execute the statement that follows ($x = "$x/" in this case) if the value in parenthesis is true.

So this piece of code will turn myFolder into myFolder/, but will leave myFile.html alone.

Note that in PHP (as in any programming language) there are several different ways to do the same thing. The following three lines are all equivalent:

$x = "$x/";    /* new string with variable */
$x = $x . "/"; /* concatenation operator   */
$x .= "/";     /* concatenation assignment */

Furthermore, the if statement may or may not have curly braces around the conditional statement and may even put everything on one line:

if (is_dir($x)) {
  $x = "$x/";
}

if (is_dir($x))
  $x = "$x/";

if (is_dir($x)) $x = "$x/";

 

Which statement you choose is a matter of personal choice. More importantly, which statement someone else chooses is a matter of their personal choice. You need to keep an open mind when reading PHP code, because you never know what the author was thinking.

    /* print the item */
    echo "<a href=\"$x\">$x</a><br />\n";

The second thing that the function does is call the echo function and pass a piece of HTML as an argument. The echo function takes its argument and adds it to the HTML that will be sent to the client browser.

Note that we did not include the parenthesis around the argument string. In PHP the parenthesis are optional.

Note also that where we wanted to include quotation marks in the string we needed to precede them with a backslash \ character. This is called escaping the quotes.

Finally, note that we ended the string with the \n. A backslash followed by the letter n stands for newline and is replaced automatically with a carriage-return.

A Little More Complicated

Did you follow that first section? Are you ready for more? Then take a look at this code:

<html>
  <head><title>My Sites</title></head>
  <body>
  <?php

  if ($_GET["dir"])
    printFolder($_GET["dir"]);
  else
    printFolder();

  function printFolder($folder = ".") {
    /* get all files and folders */
    $files = glob("$folder/*");

    /* print a link back to this folder */
    if (strcmp($folder, ".") != 0) {
      echo "back to ";
      printItem("$folder");
      echo "<br />\n";
    }

    /* print each file or subfolder */
    foreach ($files as $file)
      printItem($file);
  }

  function printItem($x) {
    if (is_dir($x)) {
      $url = "$_SERVER[PHP_SELF]?dir=$x";
      $name = substr(strrchr($x, "/") . "/", 1);
    } else {
      $url = $x;
      $name = substr(strrchr($x, "/"), 1);
    }
    echo "<a href=\"$url\">$name</a><br />\n";
  }
  ?>
  </body>
</html>

This code creates a page where file links return the file, but subfolder links return another page that displays the contents of the subfolder. If you want to know how it works, take a look at PHP Essentials: Going Deeper.

Notes

  1. The original joke was GNU, the operating system that preceded Linux. GNU stands for "GNU's Not Unix," and it was given that name because you needed to pay for Unix and Richard Stallman wanted to invent an operating system that was just like Unix in every way, but was free. Return to text.
  2. See Website Testing (Part 2): Running a Local Web Server for an explanation of setting up a local test server under Mac OS X. Return to text.
  3. This comment declaration, and in fact most of the syntax of PHP, comes from a language called C. The C language was invented in the early 1970's as an improvement of a language named B. B got its name because it was invented at Bell Labs. And you thought computer people had no sense of humor! Return to text.
  4. Why is this function named glob? The reasons are lost in time. Return to text.
  5. What we now call 'folders' were once called 'directories'. Changing the name of the function would make any pages that called the old name stop working, so the 'dir' in 'is_dir' will remain forever. Return to text.