CodeIgniter Email and HTML Table

Exclusive offer: get 50% off this eBook here
CodeIgniter 2 Cookbook

CodeIgniter 2 Cookbook — Save 50%

Over 80 recipes to help you create CodeIgniter powered applications and solve common coding problems with this book and ebook

$29.99    $15.00
by Rob Foster | November 2013 | Open Source

CodeIgniter comes with some useful libraries and functions for handling many aspects of application development. In this article by Rob Foster, author of CodeIgniter 2 Cookbook, you will look at Email and HTML tables. The CodeIgniter Email library is capable of sending plain text and HTML e-mails, with and without attachments that can be used (with a little configuration) instead of the standard PHP mail() function.

(For more resources related to this topic, see here.)

Sending HTML e-mails with CodeIgniter Email

There might be times when you wish to display formatted e-mails rather than just plain text, so you may wish to include images, text formatting, and URLs in the body of your e-mail. HTML e-mails will allow you to do this and CodeIgniter Email library can easily be set to do just that.

How to do it...

HTML e-mails can be sent by executing the following steps:

  1. Create a file email.php at /path/to/codeigniter/application/controllers/.
  2. Add the following code to the controller file email.php:

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Email extends CI_Controller { function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->library('email'); } public function index() { redirect('email/send_email'); } public function send_email() { $config['protocol'] = 'sendmail'; $config['mailpath'] = '/usr/sbin/sendmail'; $config['charset'] = 'iso-8859-1'; $config['wordwrap'] = TRUE; $config['mailtype'] = 'html'; $this->email->initialize($config); $this->email->from('from@domain.com', 'Your Name'); $this->email->to('to@domain.com'); $this->email->subject('This is a html email'); $html = 'This is an <b>HTML</b> email'; $this->email->message($html); $this->email->send(); echo $this->email->print_debugger(); } }

How it works...

In the constructor controller we load the Email library (highlighted in the following code), which provides support for us to send e-mails:

function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->library('email'); }

Next, public function index() redirects us to the function public function send_mail(), which sets some initial configuration variables for CodeIgniter Email library to work with, such as the system used to send the e-mail (in this case, sendmail), the path to send e-mail on your system, the mailtype variable (text or HTML), and so on. Take a look at the following line of code:

$config['mailtype'] = 'html';

Here, we're telling CodeIgniter to send the e-mail as HTML rather than as text.

These configuration settings are initialized (that is, passed to the Email library) and we begin to build the e-mail by setting the to, from, subject, and message attributes:

$this->email->from('from@domain.com', 'Your Name'); $this->email->to('to@domain.com'); $this->email->subject('This is a text email'); $this->email->message('And this is some content for the text email.');

Then, send the e-mail using the following code:

$this->email->send();

If all works out as planned, you should see an output similar to the following code:

Your message has been successfully sent using the following protocol:
sendmail User-Agent: CodeIgniter Date: Fri, 4 Oct 2013 08:56:59 +0200 From: "Your Name" <from@domain.com> Return-Path: <from@domain.com> To: to@domain.com Subject: =?iso-8859-1?Q?This_is_a_html_email?= Reply-To: "from@domain.com" <from@domain.com> X-Sender: from@domain.com X-Mailer: CodeIgniter X-Priority: 3 (Normal) Message-ID: <524e66bbf282f@domain.com> Mime-Version: 1.0 Content-Type: multipart/alternative; boundary="B_ALT_524e66bbf2868" This is a multi-part message in MIME format. Your email application may not support this format. --B_ALT_524e66bbf2868 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit This is an HTML email --B_ALT_524e66bbf2868 Content-Type: text/html; charset=iso-8859-1 Content-Transfer-Encoding: quoted-printable This is an <b>HTML</b> email --B_ALT_524e66bbf2868--

Sending attachments with CodeIgniter Email

There might be times when you wish to send an attachment along with the e-mail, such as an invoice to a customer for a recent purchase or perhaps an image. The CodeIgniter Email library can easily be set to do just that.

How to do it...

You can send attachments with CodeIgniter Email by executing the following steps:

  1. Create a file email.php at /path/to/codeigniter/application/controllers/.
  2. Add the following code to the controller file, email.php:

    <?php if ( ! defined('BASEPATH')) exit('No direct script access
    allowed'); class Email extends CI_Controller { function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->library('email'); } public function index() { redirect('email/send_email'); } public function send_email() { $config['protocol'] = 'sendmail'; $config['mailpath'] = '/usr/sbin/sendmail'; $config['charset'] = 'iso-8859-1'; $config['wordwrap'] = TRUE; $config['mailtype'] = 'html'; $this->email->initialize($config); $this->email->from('from@domain.com', 'Your Name'); $this->email->to('to@domain.com'); $this->email->subject('This is a html email'); $html = 'This is an <b>HTML</b> email with an attachment, <i>lovely!</i>'; $this->email->message($html); $this->email->attach('/path/to/attachment'); $this->email->send(); echo $this->email->print_debugger(); } }

How it works...

In the constructor controller we load the Email library (highlighted in the following code), which provides support to send e-mails:

function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->library('email'); }

Next, public function index() redirects us to the function, public function send_mail(), which sets some initial configuration variables for the CodeIgniter Email library to work with, such as the system used to send the e-mail (in this case, sendmail), the path to send mail on your system, the mailtype variable (text or HTML), and so on. These configuration settings are initialized (that is, passed to the Email library) and we begin to build the e-mail; setting the to, from, subject, and message attributes, as well as the path to the attachment we're sending in the e-mail (highlighted in the following code):

$this->email->from('from@domain.com', 'Your Name'); $this->email->to('to@domain.com'); $this->email->subject('This is a html email'); $html = 'This is an <b>HTML</b> email with an attachment, <i>lovely!</i>'; $this->email->message($html); $this->email->attach('/path/to/attachment');

Then, send the e-mail using the following code:

$this->email->send();

Using an HTML table with DataTable

DataTable is a free to use library that turns your normal looking html table into an interactive marvel with sortable and searchable columns and a whole lot more; we're going to use it with CodeIgniter, merging DataTable and CodeIgniter table functionality. It's simple to use and is able to handle most of the things you will need it for. Here, in this recipe, we're going to use it with DataTable to create an interactive HTML table that is sortable and searchable. It has pagination too! If you want database results, move on to the next recipe, Using an HTML table with DataTable and a database, where we'll look at populating a table from a database query.

Getting ready

For this recipe, you will need to follow the given procedure:

  1. Ensure that you've downloaded DataTable from the following link: https://datatables.net/download/
  2. Unzip the downloaded .zip file, and move the files to a location on your web server or localhost, which will be accessible by CodeIgniter. For this recipe, I have put the folder at application/views; but you can make your own choice if you wish.

How to do it...

  1. Create four files as given:
    • /path/to/codeigniter/application/controllers/table.php
    • /path/to/codeigniter/application/views/table_header.php
    • /path/to/codeigniter/application/views/table_body.php
    • /path/to/codeigniter/application/views/table_footer.php
  2. Create the controller file, table.php, and add the following code to it:

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Table extends CI_Controller { function __construct() { parent::__construct(); $this->load->library('table'); } public function index() { $tmpl = array ( 'table_open' => '<table border="0" cellpadding="4" cellspacing="0" id="example">', 'heading_row_start' => '<tr>', 'heading_row_end' => '</tr>', 'heading_cell_start' => '<th>', 'heading_cell_end' => '</th>', 'row_start' => '<tr>', 'row_end' => '</tr>', 'cell_start' => '<td>', 'cell_end' => '</td>', 'row_alt_start' => '<tr>', 'row_alt_end' => '</tr>', 'cell_alt_start' => '<td>', 'cell_alt_end' => '</td>', 'table_close' => '</table>' ); $this->table->set_template($tmpl); $this->table->set_heading(array('ID', 'First Name',
    'Last Name')); $this->table->add_row(array('1', 'Rob', 'Foster')); $this->table->add_row(array('2', 'Lucy', 'Welsh')); $this->table->add_row(array('3', 'George', 'Foster')); $this->table->add_row(array('4', 'Jackie', 'Foster')); $this->table->add_row(array('5', 'Antony', 'Welsh')); $this->table->add_row(array('6', 'Rowena', 'Welsh')); $this->table->add_row(array('7', 'Peter', 'Foster')); $this->table->add_row(array('8', 'Jenny', 'Foster')); $this->table->add_row(array('9', 'Oliver', 'Welsh')); $this->table->add_row(array('10', 'Felicity', 'Foster')); $this->table->add_row(array('11', 'Harrison', 'Foster')); $this->table->add_row(array('12', 'Mia', 'The Cat')); $data['table'] = $this->table->generate(); $this->load->view('tables/table_header'); $this->load->view('tables/table_body',$data); $this->load->view('tables/table_footer'); } }

  3. Create the view file, table_header.php, and add the following code to it:

    <html> <head> <style type="text/css" title="currentStyle"> @import "<?php echo $this->config->item('base_url') ;
    ?>application/views/DataTables-1.9.4/media/css/demo_page.css"; @import "<?php echo $this->config->item('base_url') ; ?>application/views/DataTables-1.9.4/media/css/jquery.dataTables.css"; </style> <script type="text/javascript" language="javascript" src = "<?php echo $this->config->item('base_url') ; ?> application/views/DataTables-1.9.4/media/js/jquery.js"></script> <script type="text/javascript" language="javascript" src = "<?php echo $this->config->item('base_url') ; ?> application/views/DataTables-1.9.4/media/js/jquery.dataTables.js"></script> <script type="text/javascript" charset="utf-8"> $(document).ready(function() { $('#example').dataTable(); } ); </script> </head> <body>

    Take a look at the <script> tag:

    <script type="text/javascript" charset="utf-8"> $(document).ready(function() { $('#example').dataTable(); } ); </script>

    The #example parameter is the ID of the table (detailed in the following How it works... section). Ensure that the value example in <script> and table markup is the same.

  4. Create the view file, table_body.php, and add the following code to it:

    <?php echo $table ; ?>

  5. Create the controller file, table_footer.php, and add the following code to it:

    </body> </html>

How it works...

The constructor in the table controller loads the CodeIgniter's Table library:

function __construct() { parent::__construct(); $this->load->library('table'); }

The public function index() function is called. We then define how we want our HTML table markup to appear. This is where you can place any markup for the specific CSS, using which you can style the elements of the table:

$tmpl = array ( 'table_open' => '<table border="0" cellpadding="4"
cellspacing="0" id="example">', 'heading_row_start' => '<tr>', 'heading_row_end' => '</tr>', 'heading_cell_start' => '<th>', 'heading_cell_end' => '</th>', 'row_start' => '<tr>', 'row_end' => '</tr>', 'cell_start' => '<td>', 'cell_end' => '</td>', 'row_alt_start' => '<tr>', 'row_alt_end' => '</tr>', 'cell_alt_start' => '<td>', 'cell_alt_end' => '</td>', 'table_close' => '</table>' );

Take a closer look at the table_open element of the $tmpl array. Look for the item highlighted in the preceding code. The id="example" item is used by DataTable (in the <script> tag of the file table_header.php) to apply its CSS and functionality. You can, of course, name it anything you like, but be sure to reflect that change in the JavaScript.

We then call $this->table->set_template() to apply the HTML table markup:

$this->table->set_template($tmpl);

We then set the table headers and apply the data for our rows. Ensure that the number of items in the table headers is the same as the number of items in the table data:

$this->table->set_heading(array('ID', 'First Name', 'Last Name')); $this->table->add_row(array('1', 'Rob', 'Foster')); $this->table->add_row(array('2', 'Lucy', 'Welsh')); $this->table->add_row(array('3', 'George', 'Foster')); $this->table->add_row(array('4', 'Jackie', 'Foster')); $this->table->add_row(array('5', 'Antony', 'Welsh')); $this->table->add_row(array('6', 'Rowena', 'Welsh')); $this->table->add_row(array('7', 'Peter', 'Foster')); $this->table->add_row(array('8', 'Jenny', 'Foster')); $this->table->add_row(array('9', 'Oliver', 'Welsh')); $this->table->add_row(array('10', 'Felicity', 'Foster')); $this->table->add_row(array('11', 'Harrison', 'Foster')); $this->table->add_row(array('12', 'Mia', 'The Cat'));

We then generate the table. The $this->table->generate() function will return a string of HTML, which we save in $data['table'].

$data['table'] = $this->table->generate();

The $data array our view files for rendering to the browser:

$this->load->view('tables/table_header'); $this->load->view('tables/table_body',$data); $this->load->view('tables/table_footer');

CodeIgniter 2 Cookbook Over 80 recipes to help you create CodeIgniter powered applications and solve common coding problems with this book and ebook
Published: December 2013
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

Using word_censor() for cleaning input

There may be times when you're building your application that you'll need to not only validate against unwanted data, but also check the content of that data for any unwanted words or phrases. For example, imagine that you're building a simple blogging engine and you don't want people replying to your blog posts with rude words and phrases—fair enough. So, what you need to do is to be able to look through the user input and filter out any unwanted content that might be present. CodeIgniter provides just this facility with the function word_censor(). Let's look at how to use it.

Getting ready

We're going to store our censored words in a database; so, we'll look for words that we'll use in place of actual rude words, such as rude_word_number_1, and so on.

Run the following MySQL code in your database:

CREATE TABLE `censored_words` ( `id` int(11) NOT NULL AUTO_INCREMENT, `word` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; INSERT INTO `censored_words` (`id`, `word`) VALUES (1, 'rude_word_number_1'), (2, 'rude_word_number_2'), (3, 'rude_word_number_3'), (4, 'rude_word_number_4');

We will store the censored text in another table. For want of a better title, I've called that table censor. The following code is the schema for that table, which you can run in your database:

CREATE TABLE `censor` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `body` text NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

How to do it...

  1. Create three files as shown:
    • /path/to/codeigniter/application/controllers/censor.php
    • /path/to/codeigniter/application/views/censor/create.php
    • /path/to/codeigniter/application/models/censor_model.php
  2. Create the controller file, censor.php, and add the following code to it:

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Censor extends CI_Controller { function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->helper('text'); $this->load->model('Censor_model'); } public function index() { redirect('censor/create'); } public function create() { $this->load->library('form_validation'); $this->form_validation->set_error_delimiters('', '<br />'); $this->form_validation->set_rules('name', 'Name', 'required|min_length[1]|max_length[225]|trim'); $this->form_validation->set_rules('body', 'Body', 'required|min_length[1]|max_length[2000]|trim'); if ($this->form_validation->run() == FALSE) { $this->load->view('censor/create'); } else { $query = $this->Censor_model->get_censored_words(); $censored_words = array(); foreach ($query->result() as $row) { $censored_words[] = $row->word; } $data = array( 'name' => $this->input->post('name'), 'body' => word_censor($this->input->post('body'), $censored_words, 'BOOM') ); if ($this->Censor_model->create($data)) { echo 'Entered into DB:<br /><pre>'; var_dump($data); echo '</pre>'; } } } }

  3. Create the view file create.php at /path/to/codeigniter/application/views/censor/ and add the following code to it:

    <?php echo validation_errors() ; ?> <?php echo form_open('censor/create');?> <input type="text" name="name" size="20" value= "<?php echo set_value('body') ; ?>" /> <br /> <textarea name="body"><?php echo set_value('body') ; ?></textarea> <br /> <?php echo form_submit('submit','Submit!') ; ?> <?php echo form_close() ; ?>

  4. Create the model file censor_model.php at /path/to/codeigniter/application/models/ and add the following code to it:

    <?php if ( ! defined('BASEPATH')) exit('No direct script access
    allowed'); class Censor_model extends CI_Model { function __construct() { parent::__construct(); } function get_censored_words() { $query = $this->db->get('censored_words'); return $query; } function create($data) { if ($this->db->insert('censor', $data)) { return true; } else { return false; } } }

How it works...

The constructor in our Censor class loads our support files: the helpers url and text, and our model Censor_model:

function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->helper('text'); $this->load->model('Censor_model'); }

The public function index() function redirects us to public function create() where we begin form validation. We load the form validation library and set the error delimiters, after which we set the rules for the form elements in the view file create.php at /path/to/codeigniter/application//views/censor/.

If there is an error, or the controller is being accessed for the first time, $this->form_validation->run() will equal FALSE and we shall just display the view file for the userto fill in.

However, once the form has been submitted (and assuming that there were no errors picked up by CodeIgniter's validation functionality), we now want to check the input for any unwanted words. To do that, we must first get a list of the unwanted words. As we're storing those words in the database table censored_words, we also should fetch them. So, we grab them from the database with the censor_model function get_censored_words(), and add them to an array called $censored_words:

$query = $this->Censor_model->get_censored_words(); $censored_words = array(); foreach ($query->result() as $row) { $censored_words[] = $row->word; }

We then build the $data array ready to be passed to the Censor_model function, create(). Take a look at the body element of the array, which I've highlighted in the following code:

$data = array( 'name' => $this->input->post('name'), 'body' => word_censor($this->input->post('body'), $censored_words, 'BOOM') );

Here, we call the text helper function, word_censor(), passing the string that we wish to check. In this case, the body forms items from the submitted form, along with the array of censored words as a second parameter; the third parameter is optional. Leaving the third parameter blank will cause CodeIgniter to replace a censored word with the default string ####. However, for this recipe we're replacing each censored word with the string BOOM.

The $data array is then written to the database table, censor (I really must think of a better name for that table).

Let's take it for a spin. Run the censor controller in your browser and you should see an output similar to the following screenshot:

Here, we have entered the values Rob and rude_word_number_1 TOWN. When you click on the Submit button you should see the array var_dump of $data showing:

Entered into DB: array(2) { ["name"]=> string(3) "Rob" ["body"]=> string(9) "BOOM TOWN" }

If you see BOOM TOWN, you know it has worked!

Summary

In this article, you learned the following recipes:

  • Sending HTML e-mails with CodeIgniter Email
  • Sending attachments with CodeIgniter Email
  • Using an HTML table with DataTable
  • Using word_censor()for cleaning input

CodeIgniter's HTML Table library is excellent at generating the HTML necessary for pretty much most of what you will need a table for—and, together with DataTable, can provide excellent interactive tables for your users.

Resources for Article:


Further resources on this subject:


CodeIgniter 2 Cookbook Over 80 recipes to help you create CodeIgniter powered applications and solve common coding problems with this book and ebook
Published: December 2013
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

About the Author :


Rob Foster

Rob Foster has been working in web development for almost 10 years, mainly focusing on the LAMP stack (although currently rocking a Mac). He has been developing with CodeIgniter for over 3 years, and he has worked in IT for various sectors such as public health, charity, news media, and even for the gaming industry.

Books From Packt


Programming with CodeIgniter MVC
Programming with CodeIgniter MVC

 CodeIgniter 1.7 Professional Development
CodeIgniter 1.7 Professional Development

CodeIgniter 1.7
CodeIgniter 1.7

CodeIgniter for Rapid PHP Application Development
CodeIgniter for Rapid PHP Application Development

Mastering phpMyAdmin 3.4 for Effective MySQL Management
Mastering phpMyAdmin 3.4 for Effective MySQL Management

 Mastering phpMyAdmin 3.3.x for Effective MySQL Management
Mastering phpMyAdmin 3.3.x for Effective MySQL Management

 WordPress Web Application Development
WordPress Web Application Development

 WordPress 2.7 Cookbook
WordPress 2.7 Cookbook


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
q
D
u
G
H
p
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software