Sending email with Gmail using the CodeIgniter PHP Framework

I have just implemented this functionality for OnePage and I’d like to share it in case people find it useful.
Why send email with Gmail rather than the server’s SMTP configuration?
There are a number of advantages I see for doing this:
  • Ability to develop locally and test email sending functionality without going to lengths to setup a local mail server.
  • Ability to utilise Google Apps emails to send email from emails which are on your own domain.
  • Ability to have a reference of the mail you send using this method in the “sent” folder on your Gmail account.
Right on!
So we’ve decided that’s the route we’re going to take, so lets get going! It’s rather simple actually, especially with the fantastic CodeIgniter framework and it’sEmail Class. It should work nicely for regular PHP or with other frameworks if you just take the concepts outlined here. I must also give credit to wrs from theCodeIgniter Forums, since it is his post which I have based my solution upon.
A new config file – email.php
Place the following code inside a new config file called “email.php” and put it in your application/config directory. Config files named with the same name as a library are included automatically, and this is what we’re doing here.
  1. <?php  if ( ! defined(‘BASEPATH’)) exit(‘No direct script access allowed’);
  2. /*
  3. | ——————————————————————-
  5. | ——————————————————————-
  6. | Configuration of outgoing mail server.
  7. | */
  8. $config[‘protocol’]=’smtp’;
  9. $config[‘smtp_host’]=’ssl://’;
  10. $config[‘smtp_port’]=’465′;
  11. $config[‘smtp_timeout’]=’30’;
  12. $config[‘smtp_user’]=’your gmail email’;
  13. $config[‘smtp_pass’]=’your gmail password’;
  14. $config[‘charset’]=’utf-8′;
  15. $config[‘newline’]=”\r\n”;
  16. /* End of file email.php */
  17. /* Location: ./system/application/config/email.php */
Make sure you change ‘your gmail email’ and ‘your gmail password’ appropriately.
Sending email, now sent through Gmail
Now any emails you send using the CodeIgniter Email Class will actually be sent from your Gmail account of choice:
  1. // send an email
  2. $this->load->library(’email’);
  3. $this->email->from(‘’,’Team OnePage’);
  4. $this->email->to(“”);
  5. $this->email->subject(‘A test email from CodeIgniter using Gmail’);
  6. $this->email->message(“I can now email from CodeIgniter using Gmail as my server!”);
  7. $this->email->send();
UPDATE: It seems Posterous thinks it’s clever by turning my email’s into links, even inside code. Please adjust your code accordingly 🙂
One drawback of this method
There is one drawback of this method, which is that you cannot specify the “from” email to be anything other than your Gmail email address or an email address you have associated with the Gmail account. All email will be sent from the email account you have setup as the default in your Gmail account.

Possible error – “Unable to find the socket transport “ssl” – did you forget to enable it when you configured PHP?”

If you got this error, like I did, then you need to enable SSL in your PHP config. Load up php.ini and find a line with the following:
Simply remove the “;” and then restart Apache and you’re good to go. The “;” denotes that the line is a comment, and so removing it enables the SSL extension for Apache. Credit –
That’s all!
I hope that is useful for some people 🙂 I use it mainly for local development purposes – it’s nice to be able to test everything.
Personal notes:
Other error that you may find across:

Severity: Warning

Message: fsockopen() [function.fsockopen]: unable to connect to ssl:// (Connection timed out)

Filename: libraries/Email.php

–> Possible solution is to open port 465 (You may want to consult the issue to your web hosting provider)

Code Igniter: mod rewrite

This article explains how to take away “index.php” from your CI application URLs. However, it does NOT remove the need for Index.php, which is the CI front controller i.e. even though Index.php will not appear in the URL, it still needs to be present at the top level of your site (above the /system/ directory).  To quote the User Guide,

You can easily remove this file by using a .htaccess file with some simple rules.

You need to perform the following steps to get this working:

1. Create a .htaccess file to configure the rewrite engine

2. Set $config[‘index_page’] to an empty string

3. Make sure your apache uses the mod_rewrite module

4. Make sure apache is configured to accept needed .htaccess directives

5. Restart apache and test

1. Create your .htaccess file

Create a new file named .htaccess and put it in your web directory

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

#When your application folder isn't in the system folder
#This snippet prevents user access to the application folder
#Submitted by: Fabdrol
#Rename 'application' to your applications folder name.
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin

ErrorDocument 404 /index.php

The above configuration behaves as follows:

1. If your installation is not in the server root you will need to amend the RewriteBase line from “RewriteBase /” to “RewriteBase /folder/”

2. Checks to see if someone has entered a URL starting with “system”, all requests like this get routed to index.php, this is a security feature that removes the possibility of anyone directly accessing your system folder. You can use the same syntax to hide other folders inside your root if you want.

3. If the URL doesn’t start with “system”, the web server will check to see if there is a corresponding physical resource matching the URL, such as an image, script file, or directory.

4. If such a resource exists, that resource is returned by the webserver with no rewriting performed. If no such resource exists the url is rewritten to index.php (passed to codeigniter)

Notes for Windows users:
To create this file you must open Command Prompt and type:
copy con .htaccess [Enter]
[Press CTRL + Z]
A blank .htaccess file will be created. Now you can edit it using Notepad or your favorite text editor and copy the script above.

Note: Most Windows editors will assume that you are attempting to save an .htaccess file as a file with an extension and no filename. The Crimson Editor can be used to create and save .htaccess files and other files that have no filename.

Note: If your site is placed in subfolder specify the path in the “RewriteBase /subfolder/” line.

Note: When using the above example on some systems it may be necessary to specify the uri_protocol configuration value to achieve reliable results. (Otherwise values with periods that are passed via URI will be converted to underscores in CodeIgniter 1.7.1 eg: some.value becomes some_value)

$config['uri_protocol'] = 'QUERY_STRING'; 

2. Set $config[‘index_page’]  to an empty string

Open your


and find the line that assigns $config[‘index_page’] a value, usually:

$config['index_page'] = "index.php"; 

and change it to:

$config['index_page'] = ''; 

Save the file.

3. Make sure your apache has mod_rewrite activated

This means that the apache must be configured to load the mod_rewrite module (or it might have it compiled-in). For module inclusion, usually you have to look for a line like this in httpd.conf or a file loaded by it (hint: use some quick file search utility to grep files with lines containing ‘rewrite’ string):

LoadModule rewrite_module /usr/lib/apache2/modules/ 

If you’re running Apache2 type


in the console and when prompted


to enable mod_rewrite.

On a Windows machine this line might look this way:

LoadModule rewrite_module modules/ 

If it is commented out (# in front), make sure to uncomment it and save the file. Checking if the corresponding module exists may be a good idea as well (but it usually does).

4. Make sure apache accepts needed .htaccess directives

This means that apache is explicitly configured to allow .htaccess files to override those directives that you use in your .htaccess file from step 1. above.

It seems to be sufficient if you add these two lines to your <Directory> section where you configure the document root for your CI application:

<Directory "/some/absolute/path/htdocs">
Options FollowSymLinks
AllowOverride FileInfo

There might be other Options listed, just make sure you have FollowSymLinks as well.

Should you get a 500 Internal Server Error, try the following syntax:

<Directory "/some/absolute/path/htdocs">
Options Indexes Includes FollowSymLinks MultiViews
AllowOverride AuthConfig FileInfo
Order allow,deny
Allow from all

5. Restart apache and test your application

Works? Congratulations!

Doesn’t work? Ehrrr… well, do not give up; equip yourself with patience, double check all steps above and if it still does not work, post on the forum giving all details of your setup.

How does URL rewriting work?

<IfModule mod_rewrite.c>

Do what is inside only if Apache has the mod_rewrite feature (by in place compilation, or loaded module).

RewriteEngine On 

Activate the URL rewriting engine, if not already done (in main Apache configuration file.

RewriteBase / 

Define the part of the URL that won’t change nor be used for rewriting. In fact, this part will be removed before processing, and prepended after processing. This’s a good way to use subfolder-independent rewrite rules. For example, if your CodeIgniter index.php is placed in a virtual host directory, like /tests/, set RewriteBase to /tests/.

RewriteCond %{REQUEST_FILENAME} !-f 

Condition to meet for RewriteRule activation. Here, we test if the requested filename does not exist.

RewriteCond %{REQUEST_FILENAME} !-d 

Same as above, but we test for directory existence.

RewriteRule ^(.*)$ index.php/$1 [L] 

If RewriteCond conditions are met, this rule will be applied. It inserts index.php before the requested URI. The $1 represents the part of string enclosed by parentheses in left expression. The [L] means that this rule is the last one if rule is applied (thus stopping rewriting).

Configuring mod_rewrite in the httpd.conf file

The Apache mod_rewrite docs say

While URL manipulations in per-server context are really fast and efficient, per-directory rewrites are slow and inefficient…

. If you have access to your httpd.conf file, you’ll have better performance if you configure the rewrite rules in there.

You can add something like this to your httpd.conf:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} !^(/index\.php|/img|/js|/css|/robots\.txt|/favicon\.ico)
RewriteRule ^(.*)$ /index.php/$1 [L]

Configuring mod_rewrite and virtual hosting with Apache 2.2

<VirtualHost *>
DocumentRoot /path/to/ci/directory
<Directory /path/to/ci/directory>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

WEb Programming: CI File Uploading Class (Multiple Files Too)

Sebelum masuk ke framework, yuk kita lihat kalo native-nya itu prosesnya bagaimana:

In this tutorial create 2 files
1. multiple_upload.php
2. multiple_upload_ac.phpStep
1. Create file multiple_upload.php
2. Create file multiple_upload_ac.php
3. Create folder “upload” for store uploaded files.
.4. CHMOD your upload folder to “777” by using your ftp software(change permission).
Create file multiple_upload.php
View in browser

############### Code<table width=”500″ border=”0″ align=”center” cellpadding=”0″ cellspacing=”1″ bgcolor=”#CCCCCC”>
<form action=”multiple_upload_ac.php” method=”post” enctype=”multipart/form-data” name=”form1″ id=”form1″>
<table width=”100%” border=”0″ cellpadding=”3″ cellspacing=”1″ bgcolor=”#FFFFFF”>
<td><strong>multiple Files Upload </strong></td>
<td>Select file
<input name=”ufile[]” type=”file” id=”ufile[]” size=”50″ /></td>
<td>Select file
<input name=”ufile[]” type=”file” id=”ufile[]” size=”50″ /></td>
<td>Select file
<input name=”ufile[]” type=”file” id=”ufile[]” size=”50″ /></td>
<td align=”center”><input type=”submit” name=”Submit” value=”Upload” /></td>
Create file multiple_upload_ac.php
############### Code<?php
//set where you want to store files
//in this example we keep file in folder upload
//$HTTP_POST_FILES[‘ufile’][‘name’]; = upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif
$path1= “upload/”.$HTTP_POST_FILES[‘ufile’][‘name’][0];
$path2= “upload/”.$HTTP_POST_FILES[‘ufile’][‘name’][1];
$path3= “upload/”.$HTTP_POST_FILES[‘ufile’][‘name’][2];

//copy file to where you want to store file
copy($HTTP_POST_FILES[‘ufile’][‘tmp_name’][0], $path1);
copy($HTTP_POST_FILES[‘ufile’][‘tmp_name’][1], $path2);
copy($HTTP_POST_FILES[‘ufile’][‘tmp_name’][2], $path3);

//$HTTP_POST_FILES[‘ufile’][‘name’] = file name
//$HTTP_POST_FILES[‘ufile’][‘size’] = file size
//$HTTP_POST_FILES[‘ufile’][‘type’] = type of file
echo “File Name :”.$HTTP_POST_FILES[‘ufile’][‘name’][0].”<BR/>”;
echo “File Size :”.$HTTP_POST_FILES[‘ufile’][‘size’][0].”<BR/>”;
echo “File Type :”.$HTTP_POST_FILES[‘ufile’][‘type’][0].”<BR/>”;
echo “<img src=\”$path1\” width=\”150\” height=\”150\”>”;
echo “<P>”;

echo “File Name :”.$HTTP_POST_FILES[‘ufile’][‘name’][1].”<BR/>”;
echo “File Size :”.$HTTP_POST_FILES[‘ufile’][‘size’][1].”<BR/>”;
echo “File Type :”.$HTTP_POST_FILES[‘ufile’][‘type’][1].”<BR/>”;
echo “<img src=\”$path2\” width=\”150\” height=\”150\”>”;
echo “<P>”;

echo “File Name :”.$HTTP_POST_FILES[‘ufile’][‘name’][2].”<BR/>”;
echo “File Size :”.$HTTP_POST_FILES[‘ufile’][‘size’][2].”<BR/>”;
echo “File Type :”.$HTTP_POST_FILES[‘ufile’][‘type’][2].”<BR/>”;
echo “<img src=\”$path3\” width=\”150\” height=\”150\”>”;


// Use this code to display the error or success.


if($filesize1 && $filesize2 && $filesize3 != 0)
echo “We have recieved your files”;

else {
echo “ERROR…..”;


// What files that have a problem? (if found)

if($filesize1==0) {
echo “There’re something error in your first file”;
echo “<BR />”;

if($filesize2==0) {
echo “There’re something error in your second file”;
echo “<BR />”;

if($filesize3==0) {
echo “There’re something error in your third file”;
echo “<BR />”;


CHMOD upload folder to 777 (change permission)
This step, do it when you upload to real server.
This example, I use WS-FTP, right click at upload folder > FTP Commands > CHMOD(Unix)


Kalo digabung sedikit dengan javascript untuk dynamic file input form-nya:

<script type=”text/javascript”>
function add(type){
//Create an input type dynamically.
var element = document.createElement(“input”);
var div = document.createElement(‘div’);

//simulate static variable
//if(typeof self.cnt != ‘number’)cnt = -1;
//let’s use array!

//assign attributes to the element
element.setAttribute(“type”, type);
element.setAttribute(“name”, “pic[]”);

div.setAttribute(“style”, “height:5px”);

var foo = document.getElementById(“foobar”);

//Append the element in page (in span).


<input type=”button” value=”add Picture” onclick=”add(‘file’)” />
<div id=”foobar”>&nbsp;</div>

Nah intinya kalo di CI, untuk supaya uploading class itu berjalan sebagaimana mestinya, ada beberapa hal yang musti diperhatikan keberadaannya.


$config[‘upload_path’] = ‘./uploaded/temp/’; /*$_SERVER[‘DOCUMENT_ROOT’] kalo diserver-nya*/
$config[‘allowed_types’] = ‘gif|jpg|png’;
$this->load->library(‘upload’, $config);

$this->upload->display_errors(‘<span style=”color:#cc0000″>’, ‘</span>’);


Cek kalo ada upaya upload atau tidaknya:

if(!$this->upload->do_upload(‘thumbnail’)) {

Nah kalo ada:

$file    = $this->upload->data();
$thumbnail = $file[‘file_name’];

Dan tidak lupa dengan penambahan helper custom (thanks to radhite)

kalo image, di resize dulu:


dengan definisinya:

function resizeimg($modul,$folder,$filename,$marker,$w,$h) {
$CI = &get_instance();

$config = array(
‘image_library’ => ‘GD2′,
/*’source_image’    => $_SERVER[‘DOCUMENT_ROOT’].’./resources/images/’.$modul.’/temp/’.$filename,
‘new_image’ => $_SERVER[‘DOCUMENT_ROOT’].’./resources/images/’.$modul.’/’.$folder.’/’.$filename,*/
‘source_image’    => /*$_SERVER[‘DOCUMENT_ROOT’].*/’./’.$modul.’/temp/’.$filename,
‘new_image’ => /*$_SERVER[‘DOCUMENT_ROOT’].*/’./’.$modul.’/’.$folder.’/’.$filename,
‘thumb_marker’ => $marker,
‘quality’ => 80,
‘create_thumb’ => TRUE,
‘maintain_ratio’ => TRUE,
‘width’ => $w,
‘height’ => $h

if (!$CI->image_lib->resize())
echo $folder.’ => ‘.$CI->image_lib->display_errors();
echo $CI->image_lib->clear();



<form method=”post” action=”<?php echo base_url()?>admin/artikel/edit/<?php echo $id;?>” name=”myform” id=”myform” enctype=”multipart/form-data”>

dan nama fieldnya harus sama dengan yang dipanggil di Controller,

<tr valign=”top”><td>Thumbnail</td><td>:</td><td><?php if(!empty($thumbnail)){?><img src=”<?php echo base_url().’uploaded/thumb/’.$thumbnail ?>” alt=”<?php echo $thumbnail ?>” /><br /><?php } ?><input type=”file” name=”thumbnail” value=”” /></td></tr>

Udah deh, harusnya semua akan berjalan sebagaimana mestinya.

** Tambahan:

Untuk Multiple Files upload


class Upload extends Controller {function Upload()


function index()

$this->load->view(‘upload/upload_index’); //Upload Form


function picupload()
//Load Model

$config[‘upload_path’] = ‘./uploads/’;
$config[‘allowed_types’] = ‘gif|jpg|png’;
$config[‘max_size’]    = ‘2048’; //2 meg


foreach($_FILES as $key => $value)
if( ! empty($key[‘name’]))

if ( ! $this->upload->do_upload($key))
$errors[] = $this->upload->display_errors();





$data[‘success’] = ‘Thank You, Files Upladed!’;

$this->load->view(‘upload/upload_pictures’, $data); //Picture Upload View



class Process_image extends Model {function Process_image()

//Generate random Activation code

function generate_code($length = 10){

if ($length <= 0)
return false;

$code = “”;
$chars = “abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789”;
srand((double)microtime() * 1000000);
for ($i = 0; $i < $length; $i++)
$code = $code . substr($chars, rand() % strlen($chars), 1);
return $code;



function process_pic()
//Connect to database

//Get File Data Info
$uploads = array($this->upload->data());


//Move Files To User Folder
foreach($uploads as $key[] => $value)

//Gen Random code for new file name
$randomcode = generate_code(12);

$newimagename = $randomcode.$value[‘file_ext’];

//Creat Thumbnail
$config[‘image_library’] = ‘GD2’;
$config[‘source_image’] = $value[‘full_path’];
$config[‘create_thumb’] = TRUE;
$config[‘thumb_marker’] = ‘_tn’;
$config[‘master_dim’] = ‘width’;
$config[‘quality’] = 75;
$config[‘maintain_ratio’] = TRUE;
$config[‘width’] = 175;
$config[‘height’] = 175;
$config[‘new_image’] = ‘/pictures/’.$newimagename;

//$this->load->library(‘image_lib’, $config);

//Move Uploaded Files with NEW Random name

//Make Some Variables for Database
$imagename = $newimagename;
$thumbnail = $randomcode.’_tn’.$value[‘file_ext’];
$filesize = $value[‘file_size’];
$width = $value[‘image_width’];
$height = $value[‘image_height’];
$timestamp = time();

//Add Pic Info To Database
$this->db->set(‘imagename’, $imagename);
$this->db->set(‘thumbnail’, $thumbnail);
$this->db->set(‘filesize’, $filesize);
$this->db->set(‘width’, $width);
$this->db->set(‘height’, $height);
$this->db->set(‘timestamp’, $timestamp);

//Insert Info Into Database



Semoga bermanfaat.

Lebih detailnya bisa didapatkan di:

Special thanks to Radhite for the helper