QRdvark.com

eZ Components From go to WHOA!Part 2

Contents

  1. Abstract
  2. The Template
  3. The contact file
  4. Template Variables
  5. Processing From Data
  6. Going Forward

Abstract

In part one of this series, we saw how simple and quick it was to put together a basic website using eZ Components. In part two, we will see how to create a form contact template, how to secure the form, how to sanitize and validate data coming from the form, and finally, how to safely send an email based on information from the form. You have most likely seen this on nearly any site you visit, but you would be surprised at how few of them are secured to prevent SPAM by methods of header injection.

To understand the code flow through-out this tutorial it is assumed you have read part one of this series to get you started.

The Template

Building on the template from the first example, a few additions can be made, not the least is a little structure so that we can build a menu to access different pages we build. We are, after all, building a web site.

To create the contact page, there are two methods we could employ to achieve this.

  1. Create a new file called contact.php
  2. Include a file based on a variable from GET

Each method has its merits. By creating a new file specifically to handle the contact form allows for ease of maintainence. By including a template file based on a GET variable, reduces the size of our code base, and can be controlled from a switch() in index.php thus providing a single point of access to the site. For the purposes of this tutorial, the first method will be used and a contact.php file will be created along with a contact_form.ezt template.

Templates including templates

The template is a simple form with the exception that we will now be needing a common header and footer to avoid multiple copies of HTML code and allow easier maintainence of site layout and template maintainence. Lets split up our main.ezt file into three new files. The will be called:

  1. common_header.ezt
  2. main.ezt
  3. common_footer.ezt

What we will be doing, is including the common_header.ezt and the common_footer.ezt templates from the main.ezt template. To achive this, the template engine language provides us with an include function like this:

{include "common_header.ezt" send $object}
The syntax provides a method to both include another template within the current template, and then to send the $object variable to the included template, thus making the variables available within it.

Our new template files will now look this way:

common_header.ezt

{use $object}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>{$object->title}</title>
<style type="text/css">@import url("css/style.css");</style>
</head>

<body>
<div id="container">

<div id="header">
<h1>{$object->heading}</h1>
</div>

<!-- menu -->
<div id="nav">
<p><a href="index.php">Home</a> | <a href="contact.php">Contact</a></p>
</div>
<!-- end menu -->

main.ezt

{use $object}

{include "common_header.ezt" send $object}

<!-- content area -->
<div id="content">
<h2>This is the main page</h2>
<p>{$object->content}</p>
</div>
<!-- end content -->

{include "common_footer.ezt"}

common_footer.ezt

<div class="footer">
Footer message goes here
</div>
<!-- end of container --> </div> </body>
</html>

In the common_header.ezt template file, the file begins with {use $object} just as it would in the main.ezt template, even though the index.php file, does not send the $object variable to the common_header.ezt template. The $object variable is sent to the main.ezt template. The main.ezt template, in turn, includes the common_header.ezt template, and sends the $object variable along with it.

At the bottom of the main.ezt template, another include is used to include the common_footer.ezt template. The $object variable is not sent to the template, as it makes no use of varibles, it is simply static content. Of course, as the common_footer.ezt template file makes no use of the $object variable, there is not need to put {use $object} into the that file. Only files that will use a variable, need to declare {use $object}.

The index.php file located in the html directory remains much the same as seen in the part one of this series. It sets some configuration settings and creates an object which contains the variables that will be used within the templates. The index.php file looks like this:

<?php

/*** path to the base file ***/
 
$ezBase '/www/ezcomponents/trunk/Base/src/base.php';

 if(!
file_exists($ezBase))
    {
    echo 
'Could not find base file in '.$ezBase;
    }
 else
    {
    
/*** include the base file ***/
    
include $ezBase;

    
/*** Autoload the ezcomponent classes. ***/
    
function __autoload$className ){
      
ezcBase::autoload$className );
    }

    
/*** set some config options ***/
    
$config ezcTemplateConfiguration::getInstance();

    
/*** set the template path ***/
    
$config->templatePath '/www/templates';

    
/*** set the compiled_templates path ***/
    
$config->compilePath '/www';

    
/*** Use the default configuration. ***/
    
$template = new ezcTemplate();

    
/*** create an object instance ***/
    
$object = new stdClass();

    
/*** page title ***/
    
$object->title 'My eZ Site';

    
/*** page heading ***/
    
$object->heading 'My Home Page';

    
/*** send a third content variable ***/
    
$object->content 'Home page content goes here';

    
/*** send the object to the template engine ***/
    
$template->send->object $object;
    try    {
        
/*** Compiles the template and returns the result. ***/
        
echo $template->process'main.ezt' );
        }
    catch(
Exception $e)
        {
        echo 
$e->getMessage();
        }
    }
?>

With the index.php file located in the html directory, your web tree should now look like this:

          /www -+     
                      | 
                     + html +
                      |           |
                      |          + index.php
                      | 
                     + ezcomponents
                      | 
                     + templates +
                      |                    |
                      |                   + common_footer.ezt
                      |                    |
                      |                   + common_header.ezt
                      |                    |
                      |                   + main.ezt
                      | 
                     + compiled_templates

When the index.php file accessed, the results look like this:

My Home Page

This is the main page

Home page content goes here

So, now the site begins to take shape, and adding further templates and pages becomes quite simple. The code for the contact.php page is very similar to that of the index.php page with the difference of changing the values of variables and the name of the included template. This is the contents of the contact.php file.

<?php

 
/*** begin a session ***/
 
session_start();

 
/*** path to the base file ***/
 
$ezBase '/www/ezcomponents/trunk/Base/src/base.php';

 if(!
file_exists($ezBase))
    {
    echo 
'Could not find base file in '.$ezBase;
    }
 else
    {
    
/*** include the base file ***/
    
include $ezBase;

    
/*** Autoload the ezcomponent classes. ***/
    
function __autoload$className ){
      
ezcBase::autoload$className );
    }

    
/*** set some config options ***/
    
$config ezcTemplateConfiguration::getInstance();

    
/*** set the template path ***/
    
$config->templatePath '/www/templates';

    
/*** set the compiled_templates path ***/
    
$config->compilePath '/www';

    
/*** Use the default configuration. ***/
    
$template = new ezcTemplate();

    
/*** create an object instance ***/
    
$object = new stdClass();

    
/*** page title ***/
    
$object->title 'My eZ Contact Page';

    
/*** page heading ***/
    
$object->heading 'Contact Me';

    
/*** create a form token ***/
    
$form_token md5(time());

    
/*** send the token to the template engine ***/
    
$object->form_token $token;

    
/*** send a content variable ***/
    
$object->content 'Please fill in all fields';

    
/*** send the object to the template engine ***/
    
$template->send->object $object;
    try    {
        
/*** Compiles the template and returns the result. ***/
        
echo $template->process'contact.ezt' );
        }
    catch(
Exception $e)
        {
        echo 
$e->getMessage();
        }
    }

?>

With all this in place, we can now submit the form. The form action is set to contact_proces.php. This file will need to be created. In the next section, we will deal with processing POST information.

Processing Form Data

Never Trust User Input

Never Trust User Input

Never Trust User Input

just in case you did not get that

Never Trust User Input

The most important part of scripting any application or site, is securing it. Abuse of forms is arguably the most common form of attack on web sites. Without proper validation and sanitization of input that comes to us from users, the door is open to having our form used for SPAM, or even submitting invalid information to gain access to the server.

The folks at eZ Components have taken this in mind when developing and a full suite of data validation and sanitization functions are available to ensure secure transactions between users and the application or site.

The email form we have created, has four fields that need to be checked.

  1. contact_name (required)
  2. fav_color (optional)
  3. contact_age(required)
  4. contact_email (required)
  5. contact_msg (required)

By utilizing the UserInput filter in eZ Components we can safely recieve variables from forms, and then use the values posted. Lets look at the design of our mail form and submission.

  • Set a form token
  • POST the form
  • Check form token
  • Check correct fields have been POSTed
  • Check length of POSTed fields
  • Check values of POSTed fields
  • Sanitize variables
  • Email form

These points seem rather simple and are duplicated across every site on the internet. However, not all of them are secure. Header injection in Emails is a leading avenue of SPAM from those who would use an un-secured form to send bulk emails to the world. Lets begin with the form token.

A form token is simply a value set in a session variable, and in a hidden field in the form. When the form is POSTed, the session variable must match the POST variable. If these do not match, then we know there has been an illegal access attempt. The SESSION variable is destroyed when the form is POSTed to stop reposting either by refreshing the browser, or somebody trying to exploit the form using CURL.

So lets begin with the form template itself. It is just a simple simple for that you might see on any site on the web.

{use $object}

include "common_header.ezt" send $object}

<form method="post" action="{$object->action}">
<input type="hidden" name="form_token" value="{$object->form_token}" />
<fieldset>

<legend>Please Send a Message!</legend>
<label for="sender_name"> Name:</label><br />
<input type="text" maxlength="40" class="textfield" name="sender_name" value="Anonymous Coward" id="Name" />
<br />

<label for="sender_fav_color"> Favourite Color:</label><br />
<input type="text" maxlength="40" class="textfield" name="sender_fav_color" value="" id="sender_fav_color" />
<br />

<label for="sender_age"> Age:</label><br />
<input type="text" maxlength="3" class="textfield" name="sender_age" value="" id="sender_sender_age" />
<br />

<label for="sender_email">Email: admin@qrdvark.com</label><br />
<input type="text" maxlength="248" class="textfield" name="sender_email" id="Email" value = "" />
<br />

<label for="Message">Message:</label><br />
<textarea rows="10" cols="50" name="sender_message" id="sender_message">A small message here</textarea>
<br />

<p><input type="submit" class="submit" value="Submit" /></p>
</fieldset>
</form>

{include "common_footer.ezt" send $object}

With the contact.ezt file properly located in the templates folder next to the mail.ezt template, we can now access the contact.php file and this will display the form with the form token. The form will post

<?php

?>

The result will look like this:

My eZ Site

Hello World

Of course, multiple variables can be sent and we can really begin to flesh out template. Lets change the name of the "hello_world.ezt to main.ezt and send multiple variables. The new main.ezt will look like this:

{use $title, $heading, $content}

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>{$title}</title>
</head>

<body>

<h1>{$heading}</h1>
<p>{$content}</p>

</body>
</html>

The changes to the index.php file are minimal, and only two extra variables are added. Don't forget to change the name of the hello_world.ezt to main.ezt to reflect the new name of the template.

<?php

 
/*** path to the base file ***/
 
$ezBase '/www/ezcomponents/trunk/Base/src/base.php';

 if(!
file_exists($ezBase))
    {
    echo 
'Could not find base file in '.$ezBase;
    }
 else
    {
    
/*** include the base file ***/
    
include $ezBase;

    
/*** Autoload the ezcomponent classes. ***/
    
function __autoload$className ){
      
ezcBase::autoload$className );
    }

    
/*** set some config options ***/
    
$config ezcTemplateConfiguration::getInstance();

    
/*** set the template path ***/
    
$config->templatePath '/www/templates';

    
/*** set the compiled_templates path ***/
    
$config->compilePath '/www';

    
/*** Use the default configuration. ***/
    
$template = new ezcTemplate();

    
/*** send the first variable called title ***/
    
$template->send->title 'My eZ Site';

    
/*** send heading variable to the template engine ***/
    
$template->send->heading 'Welcome to my site!';

    
/*** send a third content variable ***/
    
$template->send->content 'This is the page content';

    try    {
        
/*** Compiles the template and returns the result. ***/
        
echo $template->process'main.ezt' );
        }
    catch(
Exception $e)
        {
        echo 
$e->getMessage();
        }
    }
?>

Sending an Object

We saw above how easy it is to send a variable to the template. There is another method of sending variables that makes for less code. We could send an array, more on that later, but we could also send an object that contains our variables. We still send the object in the same manner as previously described. All we need do is create it. The content of the main.ezt will need to be changed to use the object variables.

{use $object}

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>{$object->title}</title>
</head>

<body>

<h1>{$object->heading}</h1>
<p>{$object->content}</p>

</body>
</html>

The PHP code to send the object variable to the template engine looks like this:

<?php

 
/*** path to the base file ***/
 
$ezBase '/www/ezcomponents/trunk/Base/src/base.php';

 if(!
file_exists($ezBase))
    {
    echo 
'Could not find base file in '.$ezBase;
    }
 else
    {
    
/*** include the base file ***/
    
include $ezBase;

    
/*** Autoload the ezcomponent classes. ***/
    
function __autoload$className ){
      
ezcBase::autoload$className );
    }

    
/*** set some config options ***/
    
$config ezcTemplateConfiguration::getInstance();

    
/*** set the template path ***/
    
$config->templatePath '/www/templates';

    
/*** set the compiled_templates path ***/
    
$config->compilePath '/www';

    
/*** Use the default configuration. ***/
    
$template = new ezcTemplate();

    
/*** create an object instance ***/
    
$object = new stdClass();

    
/*** page title ***/
    
$object->title 'My eZ Site';

    
/*** page heading ***/
    
$object->heading 'Welcome to my site!';

    
/*** send a third content variable ***/
    
$object->content 'This is the page content';

    
/*** send the object to the template engine ***/
    
$template->send->object $object;
    try    {
        
/*** Compiles the template and returns the result. ***/
        
echo $template->process'main.ezt' );
        }
    catch(
Exception $e)
        {
        echo 
$e->getMessage();
        }
    }
?>

When the above code is run, the output will look like this:

Welcome to my site!

This is the page content

You will also note that the title field is filled an the page title in your web browser now reads
My eZ Site

The results are similar to that of the previous method of sending variable individually, however, when sending large groups of varibles to the template engine, this is a great advantage requiring much less code.

From here on, adding a second, third or more pages is as simple as creating new PHP files, there is no need to change the template so we can use the same template, for all our pages. Lets make a second PHP file to demonstrate. We will call this page2.php and the contents will look like this:

<?php

 
/*** path to the base file ***/
 
$ezBase '/www/ezcomponents/trunk/Base/src/base.php';

 if(!
file_exists($ezBase))
    {
    echo 
'Could not find base file in '.$ezBase;
    }
 else
    {
    
/*** include the base file ***/
    
include $ezBase;

    
/*** Autoload the ezcomponent classes. ***/
    
function __autoload$className ){
      
ezcBase::autoload$className );
    }

    
/*** set some config options ***/
    
$config ezcTemplateConfiguration::getInstance();

    
/*** set the template path ***/
    
$config->templatePath '/www/templates';

    
/*** set the compiled_templates path ***/
    
$config->compilePath '/www';

    
/*** Use the default configuration. ***/
    
$template = new ezcTemplate();

    
/*** create an object instance ***/
    
$object = new stdClass();

    
/*** page title ***/
    
$object->title 'My eZ Site';

    
/*** page heading ***/
    
$object->heading 'Welcome to Page2!';

    
/*** send a third content variable ***/
    
$object->content 'This is the page2 content';

    
/*** send the object to the template engine ***/
    
$template->send->object $object;
    try    {
        
/*** Compiles the template and returns the result. ***/
        
echo $template->process'main.ezt' );
        }
    catch(
Exception $e)
        {
        echo 
$e->getMessage();
        }
    }
?>

When viewed, the above script shows the change in the heading and in the content. The benifit of this is that the programming logic, and the display logic are completely seperate. This opens up great flexibility for allowing HTML designers to weave thier magic on a single template, whilst allowing the backend developer to freely create the logic needed to run an enterprise ready site or application.

Going Forward

Of course, many sites are more than just a few static pages as we have seen here. Although, for many this is all that is required. But, most sites will have more needs and many will need dynamic content from databases or other sources. At the very least, most will have a contact form. In part two of this tutorial, we will follow the creation of a form to send an email. This will entail a template, securing the form, validation and sanitization of variables from the form, and sending an email. All this with the ready built compontents availabe from eZ.