If you’ve never heard of the Kohana PHP Framework, then today is your lucky day. Kohana is a PHP 5 framework originally based off CodeIgniter, but with many improvements. We’ll start off slow as an introduction to getting started with Kohana, and then we will really dive into to our contact form, adding all sorts of features. Enough explaining, let’s do this!

Introducing Kohana!
Before we get started, there are a few topics I recommend you have a basic understanding of, as well as a few basic server requirements you will need to meet.
What you will need to understand:
What you will need:
Remember! If you’ve used CodeIgniter, Kohana will look very familiar to you, don’t be intimidated!
The first thing we need to do is navigate to the Kohana home page and click on the download link at the top.
You will see a list of packages you can choose to include, such as an awesome payment library or perhaps you wanted to use the Google maps library. They are all great.
For now, the only package we need is the swift mailer package, make sure to include that in your Kohana download by checking the check mark. See the screenshot below:

Once you have selected swift, click download and save the zip file to your computer as seen below:

Kohana Zip Download
Create a new directory on your server wherever you like, for example, in a folder named kohanaEmail. Whatever name you like is fine, just keep it short and simple. Drag the contents of your Kohana download into your newly created directory and upload everything. This may take a minute or two so be patient.
Now that you have your files uploaded, we need to edit a configuration item or two. Kohana takes full advantage of separate config files and they can be extremely useful to you and your application.
Open up application/config/config.php and change the site domain item to your install location. For example, if you installed Kohana in a folder named ‘kohanaEmail’, then the config item would be /kohanaEmail/. See the screenshot below for an example:

Kohana Config Screenshot
Once all of the files have been uploaded, you need to navigate to the folder where you installed Kohana. For instance, if you installed Kohana in a folder named kohanaEmail, then navigate to http://yoursite.com/kohanaEmail/
Once you have done this, you should see a server configuration page, telling you wether you have passed or failed for a number of checks, and if you have passed or failed overall. Hopefully, you see something like the image below:

Kohana Install Pass
If you happened to fail on any item, no worries, check out the links on the docs or forums and do some trouble shooting.
At this point we will assumed your server has passed the check. You can now delete install.php and the .html documentation that came along with your install.
Now, ensure that applications/logs and applications/cache have a permission setting of 666.
Before we dive into our Models, Views, & Controllers, we need to setup our routing preferences.
In Kohana, just like in other PHP frameworks, the URL is routed to different controller classes and methods.
Let’s say we wanted a URL like http://mysite.com/blog/article/my-php-article/. Our class would be named blog, one of our methods would be named article, and on of the arguments accepted by the article method would be an article name, in this case, my-php-article.
All we need to do is setup what controller should be called when our home page is loaded. We want our contact page and form to show when our page is loaded.
Your config folder and file structure should now look like the images below:

Config File Structure

routes.php File
Take a minute to get familiar with the Kohana file structure. All of our files will be going into the applications folder. Kohana uses a cascading file system, a little bit like WordPress does it, which is very powerful. See the screenshot below for an idea of Kohana file layout:

Kohana File System
We will go ahead and setup our basic views and template structure. Even though this is just a beginners ‘part one’ tutorial, we want to keep our views and template flexible. You will need to create four new files in your views/ folder.
Your views/ folder should look similar to below:

View File Structure
Base template is a very flexible view file, it holds the structure and general layout for all of the rest of our views. Open up base_template.php and add the following.
<?php if (!defined('SYSPATH')) exit('No direct script access allowed'); ?>
<?php echo $header; ?>
<div id='wrap'>
<?php echo $content; ?>
</div>
<?php echo $footer; ?>
header.php will hold all of our <heade> data, title tag, and opening body/html tags. Open header.php and add the following:
<!doctype html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title><?php echo $title; ?></title> </head> <body>
footer.php is very simple and just contains some closing tags, although it could contain any copyright information, links etc. Open up footer.php and insert the following:
</body> </html>
For our contact form, we are going to use the form helper that Kohana provides. Take a minute to read through the form helper so you understand what is going on.

Form Documentation
Open up contact_form.php and insert the following. We will be adding a few more things to this later.
<?php echo form::open('contact'); ?>
<?php echo form::label('contact_name', 'Your Name'); ?>
<?php echo form::input('contact_name'); ?>
<?php echo form::label('contact_email', 'Your Email');?>
<?php echo form::input('contact_email'); ?>
<?php echo form::label('contact_subject', 'Email Subject'); ?>
<?php echo form::input('contact_subject'); ?>
<?php echo form::label('contact_message', 'Your Message'); ?>
<?php echo form::textarea('contact_message'); ?>
<?php echo form::submit('contact_submit', 'Send it!'); ?>
<?php echo form::close(); ?>
It’s now time to setup our controller to render our views…
Create a new controller in your controller file named contact.php. Open it up and paste in the following:
<?php if (!defined('SYSPATH')) exit('No direct script access allowed');
/**
* Contact_Controller - Used for validating and sending emails from form.
*
*/
class Contact_Controller extends Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
//Setup base view
$view = new View('base_template');
//Setup header
$view->header = new View('header');
//Setup header title
$view->header->title = 'Kohana Contact Form by Drew Douglass';
//Setup content view
$view->content = new View('contact_form');
//Setup footer view
$view->footer = new View('footer');
//Render view
$view->render(TRUE);
}
}
This is the absolute essentials you need to render your form. If you navigate to your Kohana install, you should now see your form, complete with all of your rendered html. With some very basic styles, you should see something like below:

Basic Form View
Now, we need to start doing the fun work, modifying our controller to handle, validate, and send the contact form request, or load the necessary views and errors.
Please note, since this is a part one tutorial, we will focus on the controller basics. There will be room for us in part two to improve the flexibility and re usability of this code.
I’ve kept the controller pretty well commented, so have a look through each line, one line at a time, and then will hit on some important bullet points and references. Open up contact.php in your controllers folder and change it to the following:
<?php if (!defined('SYSPATH')) exit('No direct script access allowed');
/**
* Contact_Controller - Used for validating and sending emails from form.
*
*/
class Contact_Controller extends Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
//Setup view without rendering
//Setup base view
$view = new View('base_template');
//Setup header
$view->header = new View('header');
//Setup header title
$view->header->title = 'Kohana Contact Form by Drew Douglass';
//Setup content view
$view->content = new View('contact_form');
//Setup footer view
$view->footer = new View('footer');
//Setup default form values so we can repopulate the form
$form = array
(
'contact_name' => '',
'contact_email' => '',
'contact_subject' => '',
'contact_message' => ''
);
//copy the form fields into the errors for later...
$errors = $form;
//Check to see if the form was submitted
if(isset($_POST['contact_submit']))
{
//Add the rules we need to validate our form
$post = new Validation($_POST);
//filter the whitespace from beginning and ends of fields
$post->pre_filter('trim');
//Add rules for contact_name
$post->add_rules('contact_name', 'required', 'standard_text', 'length[2,20]');
//Add rules for contact_email
$post->add_rules('contact_email', 'required', 'email', 'email_domain');
//add rules for subject
$post->add_rules('contact_subject', 'required', 'length[5,30]', 'standard_text');
//Add rules for message
$post->add_rules('contact_message', 'required', 'standard_text');
//If there were no errors...
if($post->validate())
{
//Load the config file with our email address defaults
//This make our app more portable
$email_config = Kohana::config_load('email');
//Send it and render the view with message.
$to = $email_config['default_email'];
$from = $this->input->post('contact_email');
$subject = $this->input->post('contact_subject');
$message = $this->input->post('contact_message');
//Add some info to the end of the message for reference
$message .= "\n\n This message was sent to you from".$this->input->post('contact_name')." and the email given is ".$from;
if(email::send($to, $from, $subject, $message, TRUE))
{
$view->content->set('form_values', $form);
$view->content->set('message', 'Your email was sent!');
$view->render(TRUE);
}
else
{
die('We had a technical error, please try again.');
}
}
//else we got errors...
else
{
//repopulate form values
$form = arr::overwrite($errors, $post->as_array());
//setup the errors
$errors = arr::overwrite($errors, $post->errors('form_errors'));
//pass the form values and errors to the view
$view->content->set('errors', $errors);
$view->content->set('form_values', $form);
//Render the view with errors and values
$view->render(TRUE);
}
}
//form was not submitted, just show it.
else
{
$view->content->set('form_values', $form);
$view->render(TRUE);
}
}
}
Now that we have the whole controller, you may have noticed there is some changes we need to make to the view, as well as a new filed or two we will need to create. Bare with me, we’re through the hardest part!
Note that the index() method above is quite large, in later series, we will review how to shorten this and make use of private methods.
Now that we have passed and attached default values and errors in the controller above, we need to display them in our view if they exist. Open up contact_form.php in your views folder and change it to the following:
<?php echo form::open('contact'); ?>
<?php if(isset($errors)) : foreach($errors as $error) : ?>
<div><strong><em><?php echo $error; ?></em></strong></div>
<?php endforeach;endif; ?>
<?php if(isset($message)): ?>
<h2><?php echo $message;?></h2>
<?php endif; ?>
<?php echo form::label('contact_name', 'Your Name'); ?>
<?php echo form::input('contact_name', $form_values['contact_name']); ?>
<?php echo form::label('contact_email', 'Your Email');?>
<?php echo form::input('contact_email', $form_values['contact_email']); ?>
<?php echo form::label('contact_subject', 'Email Subject'); ?>
<?php echo form::input('contact_subject', $form_values['contact_subject']); ?>
<?php echo form::label('contact_message', 'Your Message'); ?>
<?php echo form::textarea('contact_message', $form_values['contact_message']); ?>
<?php echo form::submit('contact_submit', 'Send it!'); ?>
<?php echo form::close(); ?>
Remember how we used $post->add_rules() to set validation rules in our controller? Now we need to setup custom error messages for our form. Kohana makes this very flexible and re usable by having us create a new file.
Create a new file named form_errors.php. Paste in the following:
<?php $lang = array ( 'contact_name' => array ( 'required' => 'The name field cannot be left blank.', 'standard_text' => 'Only standard text allowed in the name field.', 'length' => 'The name field must be between 2 and 20 characters in length.', ), 'contact_email' => array ( 'required' => 'The email field cannot be left blank.', 'email' => 'The email must be in a valid email format.', 'email_domain' => 'The email must be a valid email address.', ), 'contact_subject' => array ( 'required' => 'The subject cannot be left blank.', 'length' => 'The subject must be between 5 and 30 characters in length.', 'standard_text' => 'The subject can only contain standard text characters.', ), 'contact_message' => array ( 'required' => 'The message field cannot be left blank.', 'standard_text' => 'The message can only contain standard text characters.', ) );
Now, create a new folder in your applications folder named i18n. Inside this folder, create another folder named en_US. Place the form_errors.php file inside of applications/i18n/en_US/form_errors.php.
You can now use this file for more forms on your site, add new fields, or create a new file if you prefer.
In case you need any further clarification, your folder structure should look similar to this:

Structure
You’re almost done! Open up system/config/email.php and make a copy. Place the copy inside your applications/config folder.
Open up your email.php file in your config folder. Add the following at the bottom, and replace your email in the quotes:
$config['default_email'] = 'youremail@example.com';
Your email config file should now look something like this:

Email Config File
If you’ve followed all the steps, you should have a working Kohana contact form now. Try it out and see how the errors messages work and how the values remain intact.

Errors Found...

Success!
Our form is still relatively basic, but now that we have the framework layed out, we can go back and start adding and editing in some awesome features!
In our coming series, we are really go to take our contact form to the next level. We’ll learn how to break down our methods into smaller methods and increase re usability. We will also discuss:
Be sure to head over to Kohana and read up on the documentation and helpers, you might be surprised how much functionality Kohana comes with!
November 25th, 2009 at 10:21 am
You just got yourself a spot in Google Reader. Great tut, keep it up.
November 25th, 2009 at 11:06 pm
great tut, looking forward for the next tut ![]()
November 28th, 2009 at 5:33 pm
Great! Thanks
I will follow
Well done! Check out my quick and dirty setup tutorial over at my blog: http://breaktime.yolasite.com/
Cheers!
good tut! i think its better to setup the validation function inside of the model class. so it can be reused.
great ![]()
when will be next part?
Awesome tutorial to get started with Kohana.
Tried and works fine. Can’t wait anymore for the next part, could you please continue…………
[...] – Creating an Advanced Contact Form With Kohana [...]
[...] – Creating an Advanced Contact Form With Kohana [...]
[...] - Creating an Advanced Contact Form With Kohana [...]
I would add a reverse captcha to this as well
How about in kohana3? please provide same examples as this (composed of picture and step to step basis)
Thanks
[...] Roberto had a very good first impression of PHP5 framework Kohana, and actually liked its modules for database interactivity and cookies. With its basic template system, simple installation, and online learning resources, he’d recommend it to developers who want to save lines of code and time, but be warned, it only works with PHP 5. For those new to Kohana, he’d recommend starting with a tutorial on creating an advanced contact form. [...]
Twitter
Follow me on Twitter to keep up to date!
RSS Feed
Keep up with all of our updates by subscribing to our RSS feed!
FaceBook
Join our group on Facebook and become a fan of us!