PHP Tutorial :: Exercises (XIII)

PHP Exercise #26

Writing in a template page

Create a template page that includes several tags and write a program that gets the content of this template, replaces the tags with content stored in an array and finally saves the resulting page in a different file.

/* This is the program that replaces the template fields with real values. It stores the names and values of the fields in an array and then uses foreach() to pass thru the array and replace the fields: */
$page = file_get_contents('test_article.php');
if ($page === false) {
die("Can't read test_article.php: $php_error_msg");
$vars = array('{title}' => 'Man Bites Dog',
'{headline}' => 'Man and Dog Trapped in Biting Fiasco',
'{byline}' => 'Ireneo Funes',
'{article}' => "While walking in the park today, Bioy Casares took a big juicy bite out of his dog, Santa's Little Helper. When asked why he did it, he said, \"I was hungry.\"",
'{date}' => date('l, F j, Y'));
foreach ($vars as $field => $new_value) {
$page = str_replace($field, $new_value, $page);
$result = file_put_contents('dog_article.php', $page);
if (($result === false) || ($result == -1)) {
die("Couldn't write dog_article.php: $php_error_msg");
print 'Link to the template file: <a href="test_article.php">test_article.php</a>';
print '<br/>';
print 'Link to the article file: <a href="dog_article.php">dog_article.php</a>';
Link to the template file: test_article.php
Link to the article file: dog_article.php

PHP Exercise #27

Operating with file data

Create a text file that contains a certain amount of e-mail addresses, listed one per line, making sure that some of the adresses appear more than once in the file. Write a program that reads every line on the text file and counts how many times appears each address on the file. For each different address found in this first file, the program should write in a second text file a line containing the number of times that the address appears, followed by a comma and the address itself. The lines in the second file have to be ordered from the one that appears the most times to the one that appears the least.

$in_fh = fopen('addresses.txt', 'rb');
if (! $in_fh) {
die("Can't open addresses.txt: $php_errormsg");
// Addresses are counted with this array
$addresses = array();
for ($line = fgets($in_fh); ! feof($in_fh); $line = fgets($in_fh)) {
if ($line === false) {
die("Error reading line: $php_errormsg");
} else {
$line = trim($line);
// The address is used as the key in $addresses[]
// The value is the number of times that the address has appeared
$addresses[$line] = $addresses[$line] + 1;
if (! fclose($in_fh)) {
die("Can't close addresses.txt: $php_errormsg");
$out_fh = fopen('addresses-count.txt', 'wb');
if (! out_fh) {
die("Can't open addresses-count.txt: $php_errormsg");
foreach ($addresses as $address => $count) {
// Don't forget the line break
if (fwrite($out_fh, "$count, $address\n") === false) {
die("Can't write $count, $address: $php_errormsg");
if (! fclose($out_fh)) {
die("Can't close addresses-count.txt: $php_errormsg");
print 'Link to <a href="addresses.txt">addresses.txt</a>';
print '<br/>';
print 'Link to <a href="addresses-count.txt">addresses-count.txt</a>';

PHP Exercise #28

Operating with file data

Write a program that shows a form asking for the name of a .html file that is located below the root directory in the server. If that file exists and it can be read, display the content on screen.

To test how this works, write page-template.html in the text field and click Show File. This example is limited to display only .html files for security reasons, but otherwise it would be able to display the content of any file, either as text or binary data.

// Loads form auxiliary functions
require 'scripts/formhelpers.php';
if ($_POST['_submit_check']) {
// If validate_form() returns errors, pass them to show_form()
if ($form_errors = validate_form()) {
} else {
// The data sent is valid, then process it
} else {
// The form has not been sent, then show it
function show_form($errors = '') {
if ($errors) {
print 'You need to correct the following errors: <ul><li>';
print implode('</li><li>', $errors);
print '</li></ul>';
// The beginning of the form
print '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">';
// The name of the file
print 'File name: ';
input_text('filename', $_POST);
// The submit button
input_submit('submit', 'Show File');
// The hidden variable _submit_check
print '<input type="hidden" name="_submit_check" value="1"/>';
// The end of the form
print '</form>';
function validate_form() {
$errors = array();
// The name of the file is necessary
if (! strlen(trim($_POST['filename']))) {
$errors[] = 'Please enter a file name.';
} else {
// Creates the full name of the file from the root directory
// of the web server, a slash and the value sent
$filename = $_SERVER['DOCUMENT_ROOT'] . '/' . $_POST['filename'];
$filename = realpath($filename);
// Ensures that $filename starts with the root directory
$docroot_len = strlen($_SERVER['DOCUMENT_ROOT']);
if (substr($filename, 0, $docroot_len) != $_SERVER['DOCUMENT_ROOT']) {
$errors[] = 'File name must be under the document root directory.';
// Only .html files are allowed } elseif (strcasecmp(substr($filename, -5), '.html') != 0) {
$errors[] = 'File name must end in .html';
return $errors;
function process_form() {
// Rebuilds the full name of the file as in validate_form()
$filename = $_SERVER['DOCUMENT_ROOT'] . '/' . $_POST['filename'];
$filename = realpath($filename);
// Prints the contents of the file
print htmlentities(file_get_contents($filename));
File name: