Example 4: Intro to php

This example shows some of the basics of php. php is a good scripting language to use for preprocessing HTML. php also provides a good way to interface a database to the web. This example assumes a basic knowledge of HTML.

A php page is usually a HTML page with some php code inserted. Instead of using the file extension ".html" use the extension ".php". This tells the server program (Apache) to process the file before sending. The permissions for a php file must be set so that it is readable by the world, and executable by the user. The easiest way to do this is by using the bash command:

chmod 700 filename.php

Inside of the HTML code, you can include sections of PHP code. These sections of code will be enclosed by "<?php ... ?>". A php file with a simple echo statement to print a line would look like this:

<html>
<head>
<title>A web page</title>
</head>
<body>

<?php
echo "<h1>Hello World!</h1>" ;
echo "<p>This is php.</p>" ;
?>

</body>
</html>

You can see what this code does in example-4a.php.

php provides standard operators and control structures. Examples include if statements and for loops.

I can use php to list the files in a directory using the opendir, readdir functions and a while loop:

<html>
<head>
<title>A web page</title>
</head>
<body>

<?php
$handle = opendir('.');
while($entry = readdir($handle))
{
  echo "<a href=\"$entry\">$entry</a><br>\n";
}
closedir($handle);
?>

</body>
</html>

If you copy this code to a file in your web directory, use the extension ".php", and set the permissions to 700, you will see a directory listing. Notice that php variables begin with a "$". When a variable name is included in an echo statement, the value of the variable will be echoed.

The include and require statements are very useful. Using an include for information that is used on more than one page saves time. I make use of this over my entire site. I can update my copyright and contact notice at the bottom of all my pages by changing a single include file. The syntax for an include statement is very simple:

include filename ;

If I want to include a file with copyright information in this page, I could add the code:

<?php
include copyright.inc ;
?>

and my copyright information would be inserted into a page. I strongly recommend using this feature. While writing this example, I realized that I had an old email address in my contact information. To fix this for my entire site, all I had to do was edit one file. My entire site now has the correct address.

This simple introduction should give you a general idea of how php works. I will introduce other features in later examples



© 1996 -- 2005, Noel Schutt
E-mail me at: ski ihatespam at schutt dot org
(hint: delete " ihatespam " , and replace " at " with "@" and " dot " with ".")
Page last updated: 2004.03.31