Saturday, April 7, 2007

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:

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:
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; } } } fclose($fp); } 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. Recommended BooksProfessional PHP Programming - This Book describes all the necessary facts about PHP programming including hands-on examples like a little shop application.

No comments: