Fixing CodeIgniter Email Setup

I have been using an application I wrote in CodeIgniter that sends email notifications when an advertising link is activated or when it has expired. Several weeks ago, it suddenly stopped working. It was no longer sending email notifications as intended. I was using GMail’s SMTP server to send out the email notifications. GMail’s SMTP does require authentication. Typically, the CodeIgniter’s email preferences are located in the “config/email.php” file. It dawned on me that changing my GMail password broke my script. Here’s my email preferences found in the config/email.php file.

$config['protocol']='smtp';
$config['smtp_host']='ssl://smtp.gmail.com';
$config['smtp_port']='465';
$config['smtp_timeout']='30';
$config['smtp_user']='yourusername@gmail.com';
$config['smtp_pass']='your password';
$config['charset']='utf-8';
$config['newline']="\r\n";

So, updating the password fixed my problem.

Install CodeIgniter The Secure Way

CodeIgniter is a PHP framework for rapid application development. It’s exceptionally fast and it comes in a small footprint. Installing CodeIgniter is fairly straightforward. You just upload the CodeIgniter files and folders to the directory of your choice.

But, for a much more secure installation, you should probably move the application and system folders above your webroot folder, so that nobody has direct access to it. In addition to moving them, you also need to set the full server paths in the main index.php. You will need to edit index.php found in the main CodeIgniter folder.

Change the following entries to:

$system_path - '/full-server-path/system';
$application_folder = '/full-server-path/application';

Save. That should do it.

CodeIgniter Form_Dropdown

I had a little problem using CodeIgniter’s form_dropdown the other day. Form_dropdown produces an output similar to HTML’s form select option. I was trying to retrieve data queried from a database and display the result in a form. Well, after several test and trials, I finally got the script to work. Here’s how I did it.

Form_Dropdown

The form_dropdown function typically has 3 options. The first option is the fieldname. The second option is the option data usually laid out in an array. The third is the selected data.

form_dropdown(‘name’, array(1?=>’one’,2?=>’two’,3?=>’three’),1);

This produces:

<select name=’name’>
<option value=”1? selected=”selected”>One</option>
<option value=”2?>Two</option>
<option value=”3?>Three</option>
</select>

CodeIgniter

In CodeIgniter, I have a simple script that stores bookmarks. I categorize my bookmarks using tags. When adding bookmarks, I call on the get_dropdown_tags function in Models to retrieve all the tags and display them in array that I can use with form_dropdown. Here are my CodeIgniter entries.

Controller:

$data['tags'] = $this-&gt;links_model-&gt;get_dropdown_tags();

Models:

function get_dropdown_tags() {
  $tags = $this-&gt;db-&gt;query('select distinct tag from links');
  $dropdowns = $tags-&gt;result();
  foreach ($dropdowns as $dropdown) {
    $dropdownlist[$dropdown-&gt;tag] = $dropdown-&gt;tag;
  }
  $finaldropdown = $dropdownlist;
  return $finaldropdown;
}

Views:

In views, I’m simply calling the form_dropdown function using the $tags array passed on by the controller. It’s a pretty neat way to recall data from a database and outputting them in form_dropdown.

<?=form_dropdown(‘tag’,$tags);?>

Finally, a dropdown list that works.

Remove index.php in Codeigniter

If you work with CodeIgniter, you will soon learn fast enough that the CodeIgniter framework, by default, uses the index.php in its URL. Here’s an example of how the URL would look like with the index.php being visible.

CodeIgniter URL

http://example.com/index.php/news/article/my_article

.htaccess

To remove the index.php from the URL, you will need to add mod rewrite rules to the .htaccess file in your main CodeIgniter directory. Use this code. Change the rewrite base to your own settings.

&lt;IfModule mod_rewrite.c&gt;
RewriteEngine On
RewriteBase /ci/
 
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
 
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]
 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
&lt;/IfModule&gt;
 
&lt;IfModule !mod_rewrite.c&gt;
ErrorDocument 404 /index.php
&lt;/IfModule&gt;

config.php

In addition, you will need to edit the /application/config/config.php file. Make sure to remove index.php reference within the file.

$config['index_page'] = '';

Adding FULLTEXT Search

A few days ago, I wrote an article on how to add a search feature in CodeIgniter projects. The method I used was “Pattern Matching” using SQL’s LIKE statement. Although the LIKE statement works great, it is slow. The search will crawl in situations where there are millions of rows in a table.

An alternative method is using a FULLTEXT index search. It uses SQL’s MATCH AGAINST. To start using a FULLTEXT search, a database table will need to be indexed first. You can accomplish this by altering a table and adding FULLTEXT indexing to certain fields:

Alter Table

ALTER TABLE books ADD FULLTEXT(bookname,author,characters,synopsis);

Once a table has been indexed, you can start using MATCH AGAINST.

Match Against

I tried using CodeIgniter’s active record and MATCH AGAINST, but I could not get them to work. So, I ended up writing out the SQL statement using $this->db->query.

$match = $this-&gt;input-&gt;post('search');
$searchcount = $this-&gt;db-&gt;query("SELECT * FROM books WHERE MATCH 
  (bookname,author,characters,synopsis) AGAINST ('.$match.')");

So, if you want to increase search performance, consider using a FULLTEXT search.

Adding Search to CodeIgniter Projects

This is a little tutorial that will add a Search function to your CodeIgniter projects. As you may already know, CodeIgniter is a PHP Framework that uses the MVC model. MVC stands for Model, Views and Controller. This article assumes you’ve work with CodeIgniter before and that you are looking for a search feature that you can add to your application. To add the search feature, we will get started with the Controller.

Controller

This is assuming you already loaded your libraries, helpers and database model. Lets add the Search function.

function search()
{
$data['query'] = $this->Books_model->get_search();
$this->load->view(‘books’, $data);
}

Model

In this database query, I am searching for any matches in any of the 4 fields: bookname, author, characters and synopsis. If there are matches, it will return the results.

function get_search() {
  $match = $this->input->post(‘search’);
  $this->db->like(‘bookname’,$match);
  $this->db->or_like(‘author’,$match);
  $this->db->or_like(‘characters’,$match);
  $this->db->or_like(‘synopsis’,$match);
  $query = $this->db->get(‘books’);
  return $query->result();
}

Views

Here’s the search form.

<?=form_open(‘books/search’);?>
<?php $search = array(‘name’=>’search’,'id’=>’search’,'value’=>,);?>
<?=form_input($search);?><input type=submit value=’Search’ /></p>
<?=form_close();?>

The result can be displayed using a HTML table.

<table>
<tr><th>ID</th><th>Book</th><th>Author</th><th>Published</th><th>Price</th></tr>
<?php foreach($query as $item):?>
<tr>
<td><?= $item->id ?></td>
<td><?= $item->bookname ?></td>
<td><?= $item->author ?></td>
<td><?= $item->datepublished ?></td>
<td><?= $item->price ?></td>
</tr>
<?php endforeach;?>
</table>

Let me know what you think.

CodeIgniter: Two Ways of Writing Arrays

There are two ways of writing arrays in PHP. We will use CodeIgniter in this example. Since CodeIgniter is a MVC framework, we will look at code in models. Assuming that a form is being submitted, and data is saved to the database. In this example, we will use a function called ‘add_entry.’

The add entry function is empty at the moment.

function add_entry() {
}

We will now add post data to our function. In this example, we will use the ‘url’ and ‘anchor’ fields. To sanitize, we set both values to TRUE. We assign it to a variable called $data in an array.

function add_entry() {
$data->url = $this->input->post(‘url’,true);
$data->anchor = $this->input->post(‘anchor’,true);
}

We will now insert data to a database table called ‘bookmarks.’

function add_entry() {
$data->url = $this->input->post(‘url’,true);
$data->anchor = $this->input->post(‘anchor’,true);
$this->db->insert(‘bookmarks’, $data);
}

The other way of writing an array is this:

function add_entry() {
$data = array(
‘url’ => $this->input->post(‘url’,true),
‘anchor’ => $this->input->post(‘anchor’,true));
$this->db->insert(‘bookmarks’, $data);
}

Essentially, both are the same. Somehow, I prefer the second. It seems cleaner somehow. It seems like, I only have to deal with a single variable called $data. What’s your preferred method?

Differences Between CodeIgniter 1.7.2 and 2.0.0

It has been a year since I last touched CodeIgniter. At that time, I was working with version 1.7.2. Wanting to get back into it, I revisited the CodeIgniter website last week, and I learned that there is a new version of CodeIgniter, version 2.0.0. Last year, I created three personal projects that helped me learn how CodeIgniter works, as well as learn how MVC frameworks work in general.

I downloaded the latest version of CodeIgniter hoping that I should be able to move my old projects into the new version of CodeIgniter. Needless to say, the move was unsuccessful. I found out there are some significant changes to how CodeIgniter controllers and models are constructed between version 1.7.2 and 2.0.0. I should mention also, that there was a version in between that was released, version 1.7.3.

Here are the major differences in the way controllers and models are constructed between version 1.7.2 and version 2.0.0. In both cases, I’m using class constructors.

Version 1.7.2

Controllers

class Contact extends Controller {
  function Contact() {
    parent::Controller();
  }
}

Models

class Contact_model extends Model {
  function Contact_model() {
    parent::Model();
  }
}

Version 2.0.0

Controllers

class Contact extends CI_Controller {
  function __construct() {
    parent::__construct();
  }
}

Models

class Contact_model extends CI_Model {
  function __construct() {
    parent::__contruct();
  }
}

I might add, there are other changes I haven’t even mentioned. The biggest change is the removal of PHP 4 support. Version 2.0.0 requires PHP 5.1.6. Scaffolding is deprecated. Plugins have been removed in favor of Helpers, and few more.

Form Validation Callbacks Within CodeIgniter

There are many ways to add form validation within CodeIgniter. One way is by extending the form validation library with your own. Another way is by using callbacks. CodeIgniter support callbacks to form validation. I would like to show how callbacks can be added to the existing form validation set of rules.

Validation Rules

Here’s a typical form validation rule where the ‘url’ field is required.

$this->form_validation->set_rules(‘url’, ‘URL’,'required’ );

Validation Rules with Callbacks

This is how you add callbacks. Notice the ‘callback’ prefix.

$this->form_validation->set_rules(‘username’, ‘Username’, ‘callback_url_check’);

The Callback Function

The callback function. The ‘callback’ prefix is omitted.

function url_check() { 
  $regex = “your reg ex code here”;
  if(!preg_match($regex, $str)) {
    $this->form_validation->
    set_message(‘valid_url’, ‘Please enter a valid URL.);   return FALSE;
  } else {
    return TRUE;
  }
}

In the example above, you will need to supply your own regular expression to perform a url match. This is how you implement the callback function. It’s ideal for adding quick functions without extending the current CodeIgniter library.