Top 3 Products & Services


Dated: Aug. 12, 2004

Related Categories

PHP Programming

By Marian Heddesheimer of Site

This article will explain how to build dynamic web pages with PHP. PHP is a very popular and easy to learn script language. Regardless if you are starting to build your website, or if you are already a pro, just read on to learn more about dynamic web pages and PHP.

Why dynamic web pages?

If you have ever created a web site, you already know that maintaining very many pages is really a lot of work. Even if you never need to change the layout of the pages, you want to present the most current information on it. Sometimes the links will change, or the web pages you have linked to will disappear on the Internet. Then you need to load your page again and make all the necessary changes.

Building Dynamic Web Pages with PHPThese changes are easy to do if your whole website is very small. With 5-10 pages to maintain, you can do it by hand and page by page. With more than ten pages, it will be more difficult. If you want to have a date on each page, you must check if it is the correct one. Moreover, if you ever want to change something in the layout, you have to do this for all the pages.

So this is the big advantage of dynamic web pages: You just need a single template to start with your layout. All content within that template will be filled in dynamically from a script. If the layout has to be modified, there is no need to change every single page, you just modify the initial template and all pages will look alike.

Why PHP?

To build dynamic web pages, you can use other available techniques: Most providers offer server side includes (SSI) for your pages. This will enable you to build one template and fill in parts of the page from include files. The disadvantage with SSI is: If it comes to more complicated stuff, you want to have more power to decide what will be included in your page and what will not. For example, if you want to show a specific content only after a special date and time has passed, you will need some kind of script. With a script you can decide, that the new content will display only if the system date on the web server is set past Jan. 1st 2002 at midnight.

With scripts, you can almost do everything you like. Some kinds of scripts that are offered by the providers are available on the Internet. You can use CGI/Perl for your scripting. Almost every provider supports Perl on the web server. On the other hand, Perl is not so easy to learn and the scripts are not so easy to install. Nonetheless, there are many Perl scripts available for free or a minimal charge that you can use for your own website without knowing the language.

Another script language is ASP, but it is usually only provided on Windows web servers. In the meantime, there is also an implementation of ASP for Linux servers, but it is not yet very popular. Windows web servers are also not very popular, because they are prone to virus attacks so that even Gartner Group has recommended not to use the Internet Server from Microsoft.

A third language is Cold Fusion, but this is not very common and is not often offered by the providers.

So finally, there is PHP: A free script language, what means that it is available free of charges and free of license fees. It runs perfectly on free operating Systems like Linux and works fine with free web server software like Apache. This is one of the reasons, why most providers offer PHP as script language free with the web space.

PHP works fine with HTML: You just put some extra tags in your web page to indicate that it is not a standard HTML, but a PHP code. To tell the web server that the page may contain these special tags, you have to rename your page from "index.html" to "index.php" for example. The file extension .php indicates a PHP script that can also contain standard HTML code. Therefore, it is very easy to mix your existing HTML template with the new PHP script code.

What is PHP?

PHP was developed by Rasmus Lerdorf in 1994. It originally was an interpreter that read one line by another and tried to interpret the written code line by line. Since PHP4, it was improved by the Zend Engine from so that the code is now precompiled. The main advantage is that PHP scripts will now run much faster and the programming is more convenient. Now it is possible to define your functions after using them, which was not doable in PHP3.

PHP was meant as Personal HomePage tool, and this is where the name came from. Later it was renamed to "PHP: Hypertext Preprocessor" which is a reflective acronym because the acronym word "PHP" is contained in the long name. It is meant to be a script language that is easy to use and easy to mix with existing HTML code. Unlike using CGI/perl, there is no need to supply a special directory on the web server like cgi-bin. In most cases, there is no need to change access rights on the files that contain PHP code. The only necessary change to the HTML file is to modify the file extension from .html to .php. Some providers offer the old version PHP3 along with the new PHP4 so you have to use sometimes .php4 or .php3 for your filenames. Nonetheless, the official extension is .php, so you may have to ask your provider if there is something special on your web space.

As mentioned before, PHP is completely free and open source. This means that even the source code for PHP itself is available on the Internet. It is written in C and can be modified when necessary. Many developers are still working on the code, releasing new versions from time to time.

How to Start?

Got excited about PHP yet? So you want to know where to start? The initial start is quite easy: You should first check out if PHP is available with your web space and which version it is. It is really easy to do this. Just create a simple text file that contains theses commands:


Save this file as "info.php" and upload it to your web space. Then call it in your favorite browser by entering the appropriate URL like "".

You will get a page with lots of information or you will just see your command in the browser. If you just see the single line, either your provider does not support PHP or they are using other file extensions. Then try to rename your file to "info.php4", "info.php3" or "info.phtml". These are the most common extensions used instead of the official .php extension.

If you got the whole PHP information page, you will see the version of PHP, all the settings and server variables that are available for PHP and within your own scripts. It is a good idea to print this information for later reference.

Before you can build dynamic web pages, you should acquire a basic understanding about the language. If you already know any programming language like C, C++, VisualBasic or Java, you may find it very easy to switch to PHP. The language is pretty much like C++ and Java so that you can migrate from these languages. But even if you just have some knowledge in VisualBasic, you know what a variable and a function is, so it is not difficult to learn PHP. If you don't know anything about programming, PHP is a great tool in order to learn your first programming language for web programming.

To build your first program, you can use a simple text editor, even if it is not very comfortable. If you write more than ten lines of code, you might want a more convenient tool that can show you the correct spelling of the keywords. This feature is also known as "syntax highlighting" and there are some tools available for free.

The next step will be to learn the specific language and create a first project. A good reference is the official php web site at . Another good source for information is , where you can find articles on common PHP solutions and a forum with solutions to various questions on PHP. You will also find a variety of tutorials on PHP and there are several newsgroups related to PHP programming.

Dynamic Pages

So what about the dynamic pages? First of all, you start with a HTML page as your first template. If you are satisfied with the layout, just rename the file to .php instead of .html. You are now able to add PHP tags to the page. To keep your project clean and easy to maintain, you can collect all the things you need into one file and put it into functions. You can name this file for example ""

include "";

This will enable you to use the functions that you have defined in "" within your HTML template file. The filename has two extensions, which is common in the Unix and Linux world. The "inc" stands for a file that should be included into another file and therefore will not run on its own. The "php" stands for the PHP script language. It will prevent that the code in the file will be displayed, when anybody accidentally enters this file name into the browser URL. This will protect your intellectual property because the code from a php file is never shown in the browser.

In the dynamic file, we define the following functions:

  • show_title() will show the header for the HTML File
  • show_content() will show the main content
  • show_navigation() will show the navigation

Each function can be called anywhere in the template file by using the PHP tags:

  • <? show_content(); ?>
  • <? php show_content(); ?>
  • <script language="php"> show_content(); </script>

Each of these three lines is a valid PHP tag. The first one is commonly used but not supported by all providers. If not supported, you can use the second variation. The third one is something that is very similar to the JavaScript syntax and can be used as well. Because the first method is the shortest, it is very popular and will normally not cause any problems.

Your web pages would not be very dynamic, if you do not have more than one page. Therefore, we will provide the function calls with a parameter. A parameter is something you pass along to the function that you call. It is like telling the function more details on what it should do for you.

Parameters can also be passed with web pages. If you add a question mark after the URL, you can set one or more parameters here. We will use both types of parameters here to navigate between the pages.


You provide a set of news pages for every month. To call the news for April 2001 you can name the index page like this: "". This will show up the page "index.php" in the browser and it will also pass a parameter "id" with the value "april+2001". The plus sign is a placeholder for a blank because using blanks in a URL can cause some confusion within the script. For that reason, blanks and other special characters are encoded in the URL with special chars like the plus sign. If the plus sign itself is being used in a URL, it is encoded as "%2B".

If your user does not know anything about parameters, he/she will call the page just by using "index.php". For that reason, you may need to set a default for the parameter. In PHP, each URL parameter will be translated into a PHP variable. So your "id" parameter will be available as "$id" within PHP. The function empty($id) will check if this parameter is still empty. If this is the case, the parameter has not been passed in the URL and a default will be set to $id. This default should be the home page and is therefore set to "Home".

And this is your complete template with the PHP tags:

<? include "" ?>
<? if (empty($id)) $id = "Home" ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<title><? show_title($id) ?></title>
<? show_navigation($id) ?>
<? show_content($id) ?>

Now you want to know how the functions would work? Okay, let's start with the show_title() function:

function show_title($id)
$fp = fopen(get_filename($id), "r");
if (!$fp) return;
$line = trim(fgets($fp, 255));
echo $line;

The very first line is the function definition of show_title(). It contains the name of the function and the name of the passed parameter. In this case, the name is identical with the name we used to call the function "$id", but this is not necessary when you call a function. You can name the parameters as you like, you only have to make sure that they are placed at the correct position, if a function needs more than one parameter.

The function is then using curly brackets to enclose the function code. Everything between the opening and closing bracket belongs to that function.

The first line in the function is a call to the fopen() function that is defined within PHP. This function will open a file that is to be read or written it on the web server. The first parameter for fopen() is the name of the file. Now we only know the ID-Parameter and we have to build a filename from that. This is done by another function get_filename() that will be explained later. A second parameter will tell fopen() if the file should be opened for reading or writing. We are using the character "r" which tells the function to read the file only.

The function fopen() will return a value (which is called "return value") that is just an ID-number of the opened file. The second line in our function will check if the returned ID-number is a valid file handle. If this is not the case (the exclamation mark indicates the logical operator "not") the function will return without doing anything else.

The next statement will get a line from the opened file with the PHP function fgets(). This function reads a single line from a text file up to a specified length. In this case, we limited the length to 255 characters, because we do not expect a header to be longer than that. The return value from fgets() is not assigned to a variable, it is passed to another function trim() instead. This will strip all leading and trailing white spaces including carriage return characters.

Next, the file will be closed to tell PHP that we don't need the file handle any longer within this function. This is not really necessary if you just want to read from a file but it will save resources on the server. If you forget to close the file, it will remain open until the script ends.

The echo command will then display the line from the file. For the header we only read the first line from the file because we want to put the header line as a separate line in each text file.

To get a valid file name from the ID variable, we use this function:

function get_filename($id)
$name = "file_$id.txt";
if (file_exists($name))
return $name;
} else {
return "error.txt";

This will compose a filename from the elements "file_" the ID and ".txt". Please note that the variable "$id" can be included in the string that is provided in double quotation marks. If you use single quotation marks, the expression "$id" would show up as it is and you would get a "file_$id.txt" as result. With double quotation marks the content of $id will be evaluated and put into the string. So if the content of $id is "Home" you will get "file_Home.txt" (please note: uppercase letters are relevant in filenames on webserves).

Then, the function will check if the file exists on the server. The PHP function file_exists() returns true if the file can be found otherwise the result is false. If the file exists, the function returns the composed filename, otherwise it will return "error.txt" which should be the default error text like this:

File not found


The selected file was not found


If the specified ID is not assigned to a valid file, it will just display this text instead of the normal content. To build your dynamic content, you just need to create several text files with the name "file_{topic}.txt" were {topic} can be anything that is valid for a filename. In this example, the ID will also be displayed in the navigation link, so you may want to use something descriptive.

For example: You want to provide news for April 2001 and you name your ID "april 2001", then you need to have a file with the name "file_april 2001.txt". It is okay to have blanks in the filename as long as the operating system on the web server allows that. As you have learned before, blanks will be replaced by the URL encoding with a plus sign. The content of this file "file_april 2001.txt" could look like this:

News in April 2001

These are the latest news for april 2001

please read on to check these news ...

The first line is used as the header, all other lines are shown in the content of your page. You can use all HTML tags within this text, it will be included as it is stored in the text file.

What about the navigation? You do not want to build your navigation links by hand, do you? So we have a function here to build it from the available files:

function show_navigation($id)
if (trim($PHP_SELF) == "") $PHP_SELF = $SCRIPT_NAME;
$dir = opendir('.');
if (!$dir) return;
while ($file = readdir($dir))
if ( (ereg("^file_.*\.txt$", $file)) and (is_file($file)) )
$item = ereg_replace("^file_(.*)\.txt$", "\\1", $file);
echo ''.$item."\n";
if ($id == $item)
echo "<==";
echo " \n";

This function will browse the current directory and display all files that fit the pattern "file_*.txt". The pattern is tested with the PHP function ereg() where you can use a regular expression to test it against the given filename. Explaining regular expressions would be outside the scope of this article, just let me say that "^file_(.*)\.txt$" checks if the name starts with the string "file_" and ends with ".txt". If this is the case, another PHP function ereg_replace() removes everything from the filename except the ID that will be shown in the navigation link.

For each filename, a link will be generated to call the script itself ($PHP_SELF contains the name of the actual script) and passes the ID as a parameter. So if you click on one of these links, it will call up the appropriate content.

The last function to explain is this:

function show_content($id)


$fp = fopen(get_filename($id), "r");

if (!$fp) return;

$first = true;

while (!feof($fp))


if ($fp)


$line = fgets($fp, 1024);

if ($first)


$first = false;

} else {

echo $line;






It is pretty much similar to show_header(), but it reads the whole file line by line until the end. To avoid showing the first line (that contains the header only) there is a variable $first, defined to check if a line has already been read from the file. If this is not the case, this line will not be displayed and $first will be set to false.

Conclusion: As you can see, building dynamic web pages is not so difficult with PHP. If you don't understand each detail here, just try it out and learn as you go. Scripting languages like PHP are excellent to start programming because you will get results even with a one-liner.

Now that you've gotten free know-how on this topic, try to grow your skills even faster with online video training. Then finally, put these skills to the test and make a name for yourself by offering these skills to others by becoming a freelancer. There are literally 2000+ new projects that are posted every single freakin' day, no lie!

Previous Article

Next Article

umer's Comment
03 Fri Feb 2012
Admin's Reply:

 thank you umer :)

Dan's Comment
any chance of an example file as i can't get this to work?
13 Tue Jul 2010
Admin's Reply:

Sorry Dan but the source was taken away from us few months back. 

Hunter's Comment
Sorry, the php code keeps getting rejected. It should look similar to this: $id=$_REQUEST['id'] before: if (empty($id)) $id = "Home"
26 Sat Jun 2010
Admin's Reply:

Hunter's Comment
I think the line: is needed after the include and before the line for everything to work properly. Otherwise, everything works great!
26 Sat Jun 2010
Admin's Reply:

Hunter's Comment
I think the line: is needed after the include and before the line for everything to work properly. Otherwise, everything works great!
26 Sat Jun 2010
Admin's Reply:

Hunter's Comment
Example code download link is broken... any way to still get the example code?
26 Sat Jun 2010
Admin's Reply:

Sorry, it seems that the owner of the code has taken it offline

Tan Seryvuth's Comment
22 Thu Apr 2010
Admin's Reply:

Himasnhu's Comment
this is very gud artical it explains very easy to understand
30 Fri Oct 2009
Admin's Reply: I appreciate your comment. It just makes my day :) However, it can't replace some of the products you can come across on the left hand side. Some of my best collection of training material came from sites listed on the left side.