Postmark API Wrapper for CodeIgniter

I’ve been using Postmark and it’s API for quite a while. If you’re still sending out emails through PHP’s mail() function, you need to check out Postmark! With Postmark you can off-load those transactional emails and not have to worry about it yourself.

While there is a Postmark API Wrapper for CodeIgniter already, I felt it was unnecessary to create an entirely different Email class just to send off API requests to Postmark. Instead, this library extends the Core CI_Email class, retaining the small footprint philosophy of CodeIgniter.

Installation

  1. Download the library from Github.
  2. Copy config/postmark.php to your application/config/ folder
  3. Copy libraries/Postmark.php to your application/libraries/ folder

Configuration

There is only one setting you need to update in the config file (application/config/postmark.php) and that is your Postmark API key. You can find your API key from the Server Details -> Credentials page in your Postmark Account.

$config['postmark_api_key'] = "YOUR_API_KEY_HERE";

Loading the Library

To use the library, you will need to load it along with the Core CI_Email library (because we extend it).

$this->load->library('email');
$this->load->library('postmark');

OR

$this->load->library(array('email', 'postmark'));

Just make sure to load the Core CI_Email (email) class first.

Sending an Email

The great thing about extending the Core CI_Email class is the ability to not have to change the way you use the class! The only difference is that you will be calling functions as $this->postmark->function_name() instead of $this->email->function_name().

$this->load->library('email');
$this->load->library('postmark');

$this->postmark->from('your_example.com', 'Your Name');
$this->postmark->to('someone@example.com');
$this->postmark->cc('another@another-example.com');
$this->postmark->bcc('them@their-example.com');

$this->postmark->subject('Email Test');
$this->postmark->message('Testing the email class.');

$this->postmark->send();

Other Information

When calling $this->postmark->from(), you will have to use your Postmark API Sender Signature located on the Signatures page in your Postmark Account.

Changelog

Version 1.0
April 22nd, 2011 – Initial Release

CodeIgniter Form with Text CAPTCHA

“A CAPTCHA (Completely Automated Public Turing Test To Tell Computers and Humans Apart) is a program that protects websites against bots by generating and grading tests that humans can pass but current computer programs cannot.” — captcha.net

The current CAPTCHA system I started using is Text CAPTCHA. The Text CAPTCHA web service generates text-based CAPTCHAs which is a single question that can be easily solved by humans but cannot be solved by a robot.

Since I added comments functionality to ThePollPlace a few weeks ago, I’ve been noticing lots of spam. Lots meaning, thousands of spam comments. So I implemented Text CAPTCHA because it was simple and easy to do. Now, I’ll show you how to implement it into a form using CodeIgniter. First I’ll show you the code, then I’ll explain it.

application/controllers/example.php
class Example extends Controller {

    function Example()
    {
        parent::Controller();
    }

    function index()
    {
        // load libraries
        $this->load->library(array('session', 'form_validation'));

        // load helper
        $this->load->helper('form');

        // setup form validation
        $this->form_validation->set_rules('name',    'name',    'required');
        $this->form_validation->set_rules('email',   'email',   'valid_email');
        $this->form_validation->set_rules('url',     'url',     'prep_url');
        $this->form_validation->set_rules('captcha', 'captcha', 'required|callback_check_captcha');
        $this->form_validation->set_rules('comment', 'comment', 'required');

        if( $this->form_validation->run() )
        {
            // create comment
            die('Validated!');
        }

        // setup textCAPTCHA
        try {
            $xml = @new SimpleXMLElement('http://textcaptcha.com/api/your_api_key', NULL, TRUE);
        } catch ( Exception $e ) {
            $fallback  = '<captcha>';
            $fallback .= '<question>Is ice hot or cold?</question>';
            $fallback .= '<answer>'.md5('cold').'<answer>';
            $fallback .= '</captcha>';
            $xml = new SimpleXMLElement($fallback);
        }

        // store answers in session for use later
        $answers = array();
        foreach( $xml->answer as $hash )
        {
            $answers[] = (string)$hash;
        }
        $this->session->set_userdata('captcha_answers', $answers);

        // load vars into view
        $this->load->vars(array( 'captcha' => (string)$xml->question ));

        // load the view
        $this->load->view('example');
    }

    function check_captcha( $string )
    {
        $user_answer = md5(strtolower(trim($string)));
        $answers = $this->session->userdata('captcha_answers');

        if( in_array($user_answer, $answers) )
        {
            return TRUE;
        }
        else
        {
            $this->form_validation->set_message('check_captcha', 'Your answer was incorrect!');
            return FALSE;
        }
    }
}
application/views/example.php
<h2>Leave a Comment</h2>
<?php echo form_open('/example/index/'); ?>

    <div class="textfield">
        <?php echo form_label('Name', 'name'); ?>
        <?php echo form_error('name'); ?>
        <?php echo form_input('name'); ?>
    </div>

    <div class="textfield">
        <?php echo form_label('Email', 'email'); ?>
        <?php echo form_error('email'); ?>
        <?php echo form_input('email'); ?>
    </div>

    <div class="textfield">
        <?php echo form_label('Url', 'url'); ?>
        <?php echo form_error('url'); ?>
        <?php echo form_input('url'); ?>
    </div>

    <div class="textfield">
        <?php echo form_label($captcha, 'captcha'); ?>
        <?php echo form_error('captcha'); ?>
        <?php echo form_input('captcha'); ?>
    </div>

    <div class="textarea">
        <?php echo form_label('Comment', 'comment'); ?>
        <?php echo form_error('comment'); ?>
        <?php echo form_textarea('comment'); ?>
    </div>

    <div class="buttons">
        <button type="submit" name="submit" value="submit">Submit Comment</button>
    </div>
<?php echo form_close(); ?>

In order for Text CAPTCHA to do its job, we need to add a new form field for the question to be answered. I pass the question to the view as $captcha.

<div class="textfield">
    <?php echo form_label($captcha, 'captcha'); ?>
    <?php echo form_error('captcha'); ?>
    <?php echo form_input('captcha'); ?>
</div>

Using CodeIgniter’s Form Validation library, we need to add a new rule for the CAPTCHA. Notice we also have defined a call back: callback_check_captcha. We will use this callback to write a custom validation function to make sure our CAPTCHA was answered correctly

$this->form_validation->set_rules('captcha', 'captcha', 'required|callback_check_captcha');

Next we need to call the Text CAPTCHA service to get our random question. You will need to register to receive your api key. Be sure to replace your_api_key with the key you receive.

This try-catch statement will attempt to communicate with the Text CAPTCHA web service. If it fails, we fallback to a predefined question seamlessly. We then store all of the accepted answers into an array which is also stored in the session so we can use it for validation later.

// setup textCAPTCHA
try {
    $xml = @new SimpleXMLElement('http://textcaptcha.com/api/your_api_key', NULL, TRUE);
} catch ( Exception $e ) {
    $fallback  = '<captcha>';
    $fallback .= '<question>Is ice hot or cold?</question>';
    $fallback .= '<answer>'.md5('cold').'<answer>';
    $fallback .= '</captcha>';
    $xml = new SimpleXMLElement($fallback);
}

// store answers in session for use later
$answers = array();
foreach( $xml->answer as $hash )
{
    $answers[] = (string)$hash;
}
$this->session->set_userdata('captcha_answers', $answers);

After Text CAPTCHA is setup and initialized, we need to pass the question to our view for use in the form.

// load vars into view
$this->load->vars(array( 'captcha' => (string)$xml->question ));

CodeIgniter’s Form Validation library makes custom validation functions easy. All we need to do is check if the answer submitted is in the list of acceptable answers. If not, we fail the test and return our error message.

function check_captcha( $string )
{
    $user_answer = md5(strtolower(trim($string)));
    $answers = $this->session->userdata('captcha_answers');

    if( in_array($user_answer, $answers) )
    {
        return TRUE;
    }
    else
    {
        $this->form_validation->set_message('check_captcha', 'Your answer was incorrect!');
        return FALSE;
    }
}

That’s it! Simple enough, right? You can download the demo for the complete code.

CodeIgniter’s alternator() function


It’s surprising to me how often I find little functions for tedious tasks, that CodeIgniter already has built in. One of these functions is the alternator() function in the String Helper.

To begin using this function, make sure you have loaded the String Helper with the following code:

$this->load->helper('string');

What the alternator() function does is allow two or more items to be alternated between when iterating through a loop. Example from the CodeIgniter User Guide:

for($i = 0; $i < 10; $i++)
{
	echo alternator('string one', 'string two');
}

There is also no limit to how many parameters you can have:

...
echo alternator('one', 'two', 'three', 'four', 'five');
...

Put it to Use

What would you ever need that for? Well, what about if you are creating a list of items and every other needs class="alt" attached to it for styling differences? I run into this issue all the time.

This is how I used to do it:

<ul>
	<?php $count = 1; ?>
	<?php foreach($list as $item) : ?>
		<?php (empty($count)) ? $count = 1 : $count = 0; ?>
		<li <?=($count == 1) ? 'class="alt"' : ''?>>
			<?=$item?>
		</li>
	<?php endforeach; ?>
</ul>

And this is with the alternator() function:

<ul>
	<?php foreach($list as $item) : ?>
		<li <?=alternator('class="alt"', '')?>>
			<?=$item?>
		</li>
	<?php endforeach; ?>
</ul>

The alternator() function makes the ability to do this, much easier and cleaner than my original way. Hopefully I’ve helped someone out who had no idea this function was available.

Framework of Choice: CodeIgniter

As a developer, I am always looking for ways to increase the quality of my work and the speed at which I complete a project. One of the ways I do this is by utilizing a framework. The framework I choose is CodeIgniter.

What is CodeIgniter?

“CodeIgniter is an Application Development Framework – a toolkit – for people who build web sites using PHP. Its goal is to enable you to develop projects much faster than you could if you were writing code from scratch, by providing a rich set of libraries for commonly needed tasks, as well as a simple interface and logical structure to access these libraries. CodeIgniter lets you creatively focus on your project by minimizing the amount of code needed for a given task.” (http://codeigniter.com)

There is a key word in the definition and that is toolkit. I see and read a lot about beginning PHP developers jumping right into using a framework, such as CodeIgniter. I believe if you want to learn PHP you gotta LEARN PHP! To fully understand the concept of Model-View-Controller (MVC) and the usage of CodeIgniter you should have an understanding of PHP and how it’s used, how to utilize it, etc. It’s also important you have a basic understanding of Object-Oriented concepts.

Why CodeIgniter?

I chose CodeIgniter as my framework of choice primarily because of the swift learning curve. Learning to utilize all of CodeIgniter’s libraries took very little time and practice. The documentation is straightforward, easy to understand and very descriptive in explaining the usage of each library. Each library in CodeIgniter does a good job of handling the task it has been given. For example, the Form Validation library handles everything that has to do with creating a web form, validating a web form and re-populating data back into the form. I have spent hours in the past creating web forms, validating on both client and server side, displaying errors if any and re-populating the form. The time it takes to create a form has been cut in half (if not more) by using CodeIgniter.

CodeIgniter has also helped me find bottlenecks in my code through the use of the Profiler Library. What the profiler does is show the developer (through the browser) how much memory the application is using, what is being loaded, any data that has been posted as well as any MySQL queries that have run and the time it took to execute the query.

These are just a couple of the libraries included with CodeIgniter that help you develop your application quickly. You are not limited to only these libraries either. CodeIgniter allows you to create your own libraries and load them just like any other library. You even have the ability to extend it’s own libraries or override them completely.

I am not writing this to say CodeIgniter is the best PHP framework out there. Every developer writes code in a unique way and/or uses a different set of tools and processes to complete a project. What I am saying is, if you are a Web Developer, you should have a set of tools you use. If not, take some time to create a library for yourself or try out the variety of frameworks out there. Whatever you decide, you need to master it and your process to become the best you can be.