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 <?php echo ( $count == 1 ) ? 'class="alt"' : ''; ?>>
            <?php echo $item; ?>
        </li>
    <?php endforeach; ?>
</ul>

And this is with the alternator() function:

<ul>
    <?php foreach ( $list as $item ) : ?>
        <li <?php echo alternator( 'class="alt"', '' ); ?>>
            <?php echo $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.

Validate a Credit Card Number

This code snippet is a regular expression which checks or validates a credit card number.

The Expression

^([0-9]{4})[-|s]*([0-9]{4})[-|s]*([0-9]{4})[-|s]*([0-9]{2,4})$

This regular expression will match any of the following credit card number formats:

  • 0000-0000-0000-0000
  • 0000-0000-0000-000
  • 0000-0000-0000-00
  • 0000 0000 0000 0000
  • 0000 0000 0000 000
  • 0000 0000 0000 00
  • 0000000000000000
  • 000000000000000
  • 00000000000000

Validate Function

Here is a quick and simple validation function for a credit card number using the regular expression above and PHP’s preg_match() function:

function validate_credit_card_number( $string ) {
    if ( preg_match( '/^([0-9]{4})[-|s]*([0-9]{4})[-|s]*([0-9]{4})[-|s]*([0-9]{2,4})$/', $string ) ) {
        return TRUE;
    } else {
        return FALSE;
    }
}

Modify the Data

$string = "1234123412341234";
preg_match( '/^([0-9]{4})[-|s]*([0-9]{4})[-|s]*([0-9]{4})[-|s]*([0-9]{2,4})$/', $string, $matches );
$new_string = $matches[1] . '-' . $matches[2] . '-' . $matches[3] . '-' . $matches[4];

// New String:
// 1234-1234-1234-1234

Validate a Phone Number

This code snippet is a regular expression which checks or validates a phone number.

The Expression

^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*([\d]{3})[\.\-\s]?([\d]{4})$

This regular expression will match any of the following U.S. numbers:

  • 555 555 5555
  • (555) 555-5555
  • (555)555-5555
  • 555-555-5555
  • 555.555.5555
  • 5555555555
  • 0-000-000-0000
  • 0.000.000.0000
  • 0 000 000 0000
  • 00000000000
  • +0-000-000-0000
  • +0.000.000.0000
  • +0 000 000 0000
  • +00000000000

Why so many matches? I think it’s better, and easier to take a users input and alter it to our specifications, rather than make the user follow our guidelines.

Validate Function

Here is a quick and simple validation function for a phone number using the regular expression above and PHP’s preg_match() function:

function validate_phone_number( $string ) {
    if ( preg_match( '/^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*([\d]{3})[\.\-\s]?([\d]{4})$/', $string ) ) {
        return TRUE;
    } else {
        return FALSE;
    }
}

Modify the Data

After checking to see if the data is correct, we need to format it the way we need/want it. It’s always good to keep everything consistent.

To re-write the data, pass a third parameter to the preg_match() function, I will be using $matches. PHP will save the captures (anything wrapped in parenthesis inside the regex) to that variable, as an array.

$string = "(555) 555-5555";
preg_match( '/^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*([\d]{3})[\.\-\s]?([\d]{4})$/', $string, $matches );
$new_string = $matches[2] . '-' . $matches[3] . '-' . $matches[4];

// New String:
// 555-555-5555

Image Thumbnail Creation & Caching With CodeIgniter

How you handle the saving and display of images is very important while planning your web app. Questions you would ask yourself include: How should images be stored? What will the standard naming conventions be? How will thumbnails be created? In this article, I will be focusing on how I decided the way thumbnails would be generated in my applications.

Initial Plan

When I first started planning how images would be handled in a recent app, things went quite smoothly. I planned the logic flow like this:

  1. User uploads image
  2. PHP saves image in /assets/images/ directory
  3. PHP would loop through an array of pre-defined image dimensions and create image thumbnails from the image
  4. To display thumbnail, pass the path to thumbnail in image src attribute.

Not so hard right? WRONG!

The Problem

In one of my config files, I created an array which you could specify multiple image dimensions (height and width) for use throughout the website/application. This works BUT, what if the person coding the front-end needs different dimensions for an already uploaded image? Or, maybe the client requires a small sizing change to the thumbnail?

Looping through the array sounded like a good idea but, for small changes like these requires more work than needed. If I continued using the array method to update or add a new thumbnail dimension, every previously uploaded image would need to be updated with the new thumbnail. There has to be a better way.

The Solution

With the task at hand, a friend of mine lead me to a PHP library called phpThumb(). phpThumb() uses the GD library to create thumbnails from images on the fly. This is exactly what I needed. A way to dynamically create image thumbnails rather than pre-defined dimensions. phpThumb() was the way to go but, I didn’t want to just use the library, I wanted to understand it. What better way to understand a library than to create one yourself?

The Function

By nature, this function will be a helper function in CodeIgniter. The only library being used will be the Image Library.

To begin creating the function, we need to create a file in our ./application/helpers/ directory. I will be calling this file image_helper.php. Now we can create our function.

To generate a thumbnail of an image on the fly, we will have to pass 3 parameters to our function: The image path, the specified height, and the specified width. I will be naming the function image_thumb. You can use any name you wish.

<?php

function image_thumb( $image_path, $height, $width ) {
    // code
}

/* End of file image_helper.php */
/* Location: ./application/helpers/image_helper.php */

In order to use the Image Library of CodeIgniter, we need the CodeIgniter object available to us. In the current state of the function, if we used $this->load->library('image_lib') to load the Image Library, the function would throw error. This is because helpers in CodeIgniter are not classes but rather a collection of functions.

So, how do we use CodeIgniter’s libraries in our helper? CodeIgniter’s got us covered! CodeIgniter has a function called get_instance() which returns the CodeIgniter super object. We will use it like so:

function image_thumb( $image_path, $height, $width ) {
    // Get the CodeIgniter super object
    $CI =& get_instance();
}

It is important to be aware that we are passing the get_instance() function by reference. Passing by reference allows us to use the original CodeIgniter object (already in memory) rather than creating a copy of it (duplicating memory). Passing variables and functions by reference comes in handy when optimizing your PHP application. But, that is another article for another day.

The next thing we must do is figure out where to store the generated thumbnails. This is for caching purposes. When the function is used, the original image path is passed to it. To get the directory path from the image path we will use PHP’s built-in dirname() function.

For example: I would pass assets/images/picture-1/picture-1.jpg as the original image file path and dirname('assets/images/picture-1/picture-1.jpg') would return assets/images/picture-1/ as the directory to save the generated thumbnails. Notice I will not pass the path with a beginning slash (/).

We also need to construct the filename we want for our thumbnail image. I will make the filename height_width.jpg because all of my images are grouped inside their own folders. Take a look at the updated function:

function image_thumb( $image_path, $height, $width ) {
    // Get the CodeIgniter super object
    $CI =& get_instance();

    // Path to image thumbnail
    $image_thumb = dirname( $image_path ) . '/' . $height . '_' . $width . '.jpg';
}

Now, the way caching works in this function is if the image thumbnail path ($image_thumb) exists, the thumbnail has already been created therefore does not need to be generated again. If the file does not exists, we need to create it!

To create the image thumbnail, we need to load CodeIgniter’s Image Library.

function image_thumb( $image_path, $height, $width ) {
    // Get the CodeIgniter super object
    $CI =& get_instance();

    // Path to image thumbnail
    $image_thumb = dirname( $image_path ) . '/' . $height . '_' . $width . '.jpg';

    if ( !file_exists( $image_thumb ) ) {
        // LOAD LIBRARY
        $CI->load->library( 'image_lib' );
    }
}

Before we can do anything with the Image Library, we need to configure it.

function image_thumb( $image_path, $height, $width ) {
    // Get the CodeIgniter super object
    $CI =& get_instance();

    // Path to image thumbnail
    $image_thumb = dirname( $image_path ) . '/' . $height . '_' . $width . '.jpg';

    if ( !file_exists( $image_thumb ) )
    {
        // LOAD LIBRARY
        $CI->load->library( 'image_lib' );

        // CONFIGURE IMAGE LIBRARY
        $config['image_library']    = 'gd2';
        $config['source_image']     = $image_path;
        $config['new_image']        = $image_thumb;
        $config['maintain_ratio']   = TRUE;
        $config['height']           = $height;
        $config['width']            = $width;
        $CI->image_lib->initialize( $config );
    }
}

I am using GD2 as the image library. You can use what you wish, gd2 is default. The source_image config variable is the path to the original (full-size) image. The new_image config variable is the path to our specified thumbnail image. CodeIgniter will save the thumbnail to this path. I have set maintain_ratio to TRUE so that CodeIgniter automatically resizes our image to the best dimensions to fit our specified height and width, without distorting the image in any way.

Finally, we initialize our configuration:

$CI->image_lib->initialize( $config );

After configuration is complete, we need to process the image to generate our thumbnail. Do this by running $CI->image_lib->resize(). After resizing the image, we need to reset all values used by the Image Library when processing an image. Do this by running $CI->image_lib->clear().

Last but not least, we need to return our thumbnail! In my function, I have returned the HTML image tag (img) with the thumbnail path already in the source (src) attribute. You can just return the path if you want, just return the generated src path.

The Complete Function

<?php

function image_thumb( $image_path, $height, $width ) {
    // Get the CodeIgniter super object
    $CI =& get_instance();

    // Path to image thumbnail
    $image_thumb = dirname( $image_path ) . '/' . $height . '_' . $width . '.jpg';

    if ( !file_exists( $image_thumb ) ) {
        // LOAD LIBRARY
        $CI->load->library( 'image_lib' );

        // CONFIGURE IMAGE LIBRARY
        $config['image_library']    = 'gd2';
        $config['source_image']     = $image_path;
        $config['new_image']        = $image_thumb;
        $config['maintain_ratio']   = TRUE;
        $config['height']           = $height;
        $config['width']            = $width;
        $CI->image_lib->initialize( $config );
        $CI->image_lib->resize();
        $CI->image_lib->clear();
    }

    return '<img src="' . dirname( $_SERVER['SCRIPT_NAME'] ) . '/' . $image_thumb . '" />';
}

/* End of file image_helper.php */
/* Location: ./application/helpers/image_helper.php */

Using the Function

In order to use the function, you will need to load the helper, either in your controller or the application autoload file.

General usage in View:

<?php echo image_thumb( 'assets/images/picture-1/picture-1.jpg', 50, 50 ); ?>

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.

WordPress ‘Fetch Feed’ Plugin

‘Fetch Feed’ is a RSS retrieval and caching plugin for WordPress. You can use it to parse any RSS feed for displaying on your site. The beauty of this plugin is that you are not limited to how you display your feed. All you need to know is a basic understanding of PHP foreach loops and array/object structure.

Installation

  1. Download the file and unzip it. Upload the ‘fetch-feed’ folder to your ~/wp-content/plugins/ directory
  2. Make sure the ~/wp-content/plugins/fetch-feed/cache/ directory is writeable
  3. Activate the plugin through the ‘Plugins’ admin menu in WordPress

Usage

To begin using the function we need to pass the url to the RSS feed we would like to work with and save the result in a variable. I will be using $xml. We will also specify in the second parameter, the amount in minutes we would like the feed cached for:

// Retrieve RSS from http://jrtashjian.com and cache for 60 minutes
$xml = fetch_feed( "http://jrtashjian.com/feed/", 60 );

After the function retrieves the RSS you can loop through the object using a foreach loop, like so:

<h2><?php echo $xml->channel->title; ?></h2>
<ul>
    <?php foreach ( $xml->channel->item as $item ) : ?>
        <li><a href="<?php echo $item->link; ?>"><?php echo $item->title; ?></a></li>
    <?php endforeach; ?>
</ul>

Limit Words in a String

While developing websites, I’ve frequently run into clients who would like a news system integrated on their site. A news system consists of a list of articles, usually a summary at first, and when an article has been selected, the full article is displayed. So, how do you extract the summary from the content without duplicating content?

If you wanted to do this effect quickly, you could just use the function substr(). However, the substr() function only limits the number of characters being displayed. The returned result would be an excerpt of text that may or may not have the ending word cut-off.

The purpose behind this function is to limit the number of words displayed in such a way that the ending word is not cut-off. Personally, I think this small change makes the site look a little nicer.

function limit_words( $string, $word_limit ) {
    $words = explode( " ", $string );
    return implode( " ", array_splice( $words, 0, $word_limit ) );
}

To use this function, pass the text you would like to extract the excerpt from, as $string. Then, set the number of words you would like to display as $word_limit. The function will return the excerpt as a string.

The function separates the string where it finds a space, therefore separating each word using the explode() function. Each word is put into an array called $words. We then cut out the excerpt using the number of words we would like to display ($word_limit) starting from the beginning using the array_splice() function. With the excerpt extracted from the full text, we then recreate the string by adding spaces after each key (word) in the array using the implode() function.

# Example Usage
$content = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
echo limit_words( $content, 20 );

The above example would output this result:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut

Simple function, Nice results. Enjoy!

Recursive Delete with FTP

I was recently creating an administration application for a client. The app involved working with files and directories as well as uploading and deleting files or directories. While I was developing, I ran into an issue that required a special function: recursive delete.

A recursive function is a function that has the ability to call itself (recursion). I ran into this problem while trying to delete a directory containing files and/or other directories. I was using FTP at the time so, the function will be written as such. It can be easily ported to using filesystem functions by following the same logic/flow.

Anyway, the use of ftp_rmdir() was not enough. Using it to delete a directory containing files or folders only throws an error stating that the folder you are trying to delete contains other files. It was a little disappointing to see that PHP does not have a recursive delete function built in. So, I decided to write my own function. It works very well, it is small and it runs fast!

Well, here is the code:

# server credentials
$host = "ftp server";
$user = "username";
$pass = "password";

# connect to ftp server
$handle = @ftp_connect( $host ) or die( "Could not connect to $host" );

# login using credentials
@ftp_login( $handle, $user, $pass ) or die( "Could not login to $host" );

function recursiveDelete( $directory ) {
    # here we attempt to delete the file/directory
    if( !( @ftp_rmdir( $handle, $directory ) || @ftp_delete( $handle, $directory ) ) ) {
        # if the attempt to delete fails, get the file listing
        $filelist = @ftp_nlist( $handle, $directory );

        # loop through the file list and recursively delete the FILE in the list
        foreach ( $filelist as $file ) {
            recursiveDelete( $file );
        }

        #if the file list is empty, delete the DIRECTORY we passed
        recursiveDelete( $directory );
    }
}

The comments explain what is going on but, I will explain a little more right now. Basically, you pass the directory you want to delete to the function. The function will try to delete the file/directory that was passed to it. If the function fails to delete the file/directory, it will attempt to enter the directory and get a file list. The function then loops through the file list and calls itself by passing the file or directory from the list. It will repeat this until there are no more files or directories inside the directory you passed for removal. Once that is complete, it will re-attempt to delete the directory you passed to it.

Thats it! Very small script, yet very powerful. Be careful when creating these kinds of functions as you don’t want the function to accidentally delete more than you intended. Just a quick note about the function, make sure you include a trailing slash at the end of the directory! If you forget to, this function will try and delete the files and directories where the directory you passed is contained. It’s a good habit to get into anyway. I was flooding the FTP server at work with requests to delete directories I didn’t want to delete because I forgot to add the trailing slash! Good thing the file permissions stopped it!

Site Launched!

Hey everyone! My name is JR Tashjian and I am a Web Developer living and working in New York.

I started this blog because I wanted to write about what I do and what I learn as well as educate any readers wanting to learn more about Web Development. I will be focusing on the Back-End (server side) coding of projects using PHP and MySQL. I will also write a little about Front-End (client side) coding using HTML, CSS and JavaScript. As for post consistency, I haven’t set anything nor do I plan to. I will write articles as I have time but, I will aim for one or two posts a week.

Well, I am very excited about this launch! I hope everyone who reads my articles will find this site a valuable resource for learning Web Development. If you have any topics you would like me to write about or have a question you want answered, feel free to email and I will get back to you as soon as I can.

Check back often for updates! While your waiting, get the feed!