What is this chapter for? I hope to use this first chapter to act as a primer for all other chapters and projects in the book. I would like you to use the introduction as a common resource containing all of the resources shared by the projects in the book.
The introduction will cover the installation of third-party software, libraries, helpers, and so on, that are required by the projects in the later chapters. By keeping these resources in this chapter, the projects aren't swamped with repetitive code and the project code can be kept as clean and concise as possible.
In this chapter, we will cover the following topics:
An overview of the book
Downloading CodeIgniter
Downloading and installing Twitter Bootstrap
Creating common header and footer files used for all projects
Installing Sparks
Common language items
The common resources used in this book are discussed in upcoming sections.
Every project in the chapters in this book uses Twitter Bootstrap. We will download Bootstrap and find a good place for it in our filesystem. We will then create the header and the footer files. All projects in the book will call these header and footer files (using the CodeIgniter function $this->load->view()
to display views). However, these projects will not actually contain the code for the header and footer—only the working code between the header and footer (what you might think of as the stuff in between the <body>
and </body>
tags) will be detailed in each project.
We'll need a copy of CodeIgniter to start with. This book isn't really aimed at the beginner, so the chances are reasonably high that you already have a copy of CodeIgniter installed or at least know your way around enough to skip this part; however, it does make sense to briefly go through the installation of CodeIgniter so that we have something to talk about in later chapters!
First things first, go to https://ellislab.com/codeigniter/user-guide/installation/downloads.html. You'll see something similar to what is shown in the following screenshot. This is the CodeIgniter download page. At the time of writing, the current CodeIgniter version is 2.2.0; this is why the screenshot says Current version next to version 2.2.0; however, whichever version is the latest when you're reading this book is the version you want to use.
Click on the Current version link, and CodeIgniter will begin to download.

Once it's downloaded, navigate to where you have saved the file; this will be a compressed archive. Unpack it and move the contents of that file to a folder within your web root.
Specific details of routing, configuration, and database use are in each chapter (these details are specific to that particular chapter).
You may experience errors if you run CodeIgniter on newer versions of PHP. There is a hack for this that is explained at https://ellislab.com/forums/viewthread/244510/. A poster called milan.petrak has described a work around. It can be summed up as follows:
Open the
/path/to/codeigniter/system/core/common.php
file and find the line 257.Find the following line:
$_config[0] =& $config; with return $_config[0]; return $_config[0] =& $config;
Save the
common.php
file.
This will likely be permanently fixed in later releases of CodeIgniter, but for now, this is the fix.
Twitter Bootstrap is a frontend HTML5 framework that allows anyone to easily construct reliable interfaces. At the time of writing, the version of Bootstrap used is version 3.1.1.
We will use Twitter Bootstrap throughout this book to provide the framework for all view files and templates. We will look at how to download Twitter Bootstrap and how to install it in the CodeIgniter filesystem.
Firstly, we will need to download the Twitter Bootstrap files. To do that, perform the following steps:
Open your web browser and go to the Bootstrap download link at http://getbootstrap.com/getting-started. You'll see something similar to what is shown in the following screenshot:
Find the Download Bootstrap link and click on it (as indicated in the preceding screenshot); the download will start automatically.
Once the download is finished, go to its location on your machine and unpack the archived file. Inside the unpacked file, you should see something similar to what is shown in the following structure:
bootstrap/ ├── css/ │ ├── bootstrap-theme.css │ ├── bootstrap-theme.css.map │ ├── bootstrap-theme.min.css │ └── bootstrap.css │ └── bootstrap.css.map │ └── bootstrap.min.css ├── js/ │ ├── bootstrap.js │ └── bootstrap.min.js └── fonts/ ├── glyphicons-halflings-regular.eot ├── glyphicons-halflings-regular.svg ├── glyphicons-halflings-regular.ttf └── glyphicons-halflings-regular.woff
Move the bootstrap
folder to your CodeIgniter installation so that the file hierarchy looks like the following:
/path/to/web/root/ ├── application/ └── views/ ├── common ├── header.php ├── footer.php ├── system/ ├── bootstrap/ ├── index.php ├── license.txt
In the preceding tree structure, the application
and system
directories are to do with CodeIgniter, as are the index.php
and license.txt
files; however, the bootstrap
directory contains the contents of your Bootstrap download.
I have also indicated the location of the common header.php
and footer.php
files. These files are used throughout the book and act as a wrapper for every other view file.
It is possible to remove index.php
from the web browser address bar when CodeIgniter is running. This can be done by following these steps:
Create or open a
.htaccess
file. If a.htaccess
file does not already exist, you can create one using the following:Linux/Mac: Open a terminal window and type the following:
touch /path/to/CodeIgniter/.htaccess
Windows: Create a text file in your CodeIgniter root, naming it
file.htaccess
. Hold down the Windows key and then press R to open the Run dialogue. Enter the following command and click on OK:ren "C:\path\to\CodeIgniter\file.htaccess" .htaccess
Once your
.htaccess
file is opened, write the following lines at the top of the file:<IfModule mod_rewrite.c> RewriteEngine on RewriteCond $1 !^(index\.php|images|robots\.txt) RewriteRule ^(.*)$ index.php/$1 [L] </IfModule>
For a long time, you had to search the Internet and download code from various places—blogs, code repositories, and so on—to find and use extensions, libraries, and other useful snippets of code for CodeIgniter. Useful installations for CodeIgniter were spread across the Internet; as such, they might have been hard to locate. Sparks acts as a single point of reference for extensions of CodeIgniter. It's simple to install and use and contains thousands of useful add-ons for CodeIgniter:
If you are using a Mac or Linux, then the command-line interface is open to you. Using the terminal application on your system, navigate to the root of your CodeIgniter application and enter the following line:
php -r "$(curl -fsSL http://getsparks.org/go-sparks)"
If your installation was successful, you should see something similar to the following:
user@server:/path/to/codeigniter$ php -r "$(curl -fsSL http://getsparks.org/go-sparks)" Pulling down spark manager from http://getsparks.org/static/install/spark-manager-0.0.9.zip ... Pulling down Loader class core extension from http://getsparks.org/static/install/MY_Loader.php.txt ... Extracting zip package ... Cleaning up ... Spark Manager has been installed successfully! Try: `php tools/spark help`
If you are using Windows, then you will need to download Sparks and unpack it manually; to do that, follow these instructions or check out the instructions on the GetSparks website for the latest version:
Create a folder called
tools
in the top level (root) or in your CodeIgniter directory.Go to http://getsparks.org/install.
Go to the Normal Installation section and download the Sparks package.
Unpack the download into the
tools
folder you created in step 1.Download the Loader class extension from http://getsparks.org/static/install/MY_Loader.php.txt.
Rename the file
MY_Loader.php.txt
toMY_Loader.php
and move it to theapplication/core/MY_Loader.php
location in your CodeIgniter instance.
Now that Sparks is installed in your CodeIgniter instance, you can begin to install extensions and packages.
To install a package from Sparks, type the following in the command-line window:
php tools/spark install [Package Version] Spark Name
Here, Package Version
is the specific version of the Spark you wish to install. You are not required to state the version and, if you it out, Sparks will download the latest version by default. Spark Name
is the name of the Spark you wish to install; for example, to install example-spark
(version 1.0.0), which comes with the default installation, type the following in the command-line window:
php tools/spark install -v1.0.0 example-spark
If the installation was successful, you should see something similar to the following:
user@server:/path/to/codeigniter$ php tools/spark install -v1.0.0 example-spark [ SPARK ] Retrieving spark detail from getsparks.org [ SPARK ] From Downtown! Retrieving spark from Mercurial repository at https://url/of/the/spark/repo [ SPARK ] Spark installed to ./sparks/example-spark/1.0.0 - You're on fire!
Every project throughout this book will use the common header and footer files that we will create here; navigation menus will be different for each project and, as such, we will build these in the project's chapter themselves. But for now, let's look at the common header and footer files:
Create the
header.php
file at/path/to/codeigniter/application/views/common/
and add the following code to it:<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <link rel="shortcut icon" href="<?php echo base_url('bootstrap/ico/favicon.ico'); ?>"> <title><?php echo $this->lang->line('system_system_name'); ?></title> <!-- Bootstrap core CSS --> <link href="<?php echo base_url('bootstrap/css/bootstrap.min.css'); ?>" rel="stylesheet"> <!-- Bootstrap theme --> <link href="<?php echo base_url('bootstrap/css/bootstrap-theme.min.css'); ?>" rel="stylesheet"> <!-- Custom styles for this template --> <link href="<?php echo base_url('bootstrap/css/theme.css');?>" rel="stylesheet"> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body role="document"> <!-- END header.php --> <div class="container theme-showcase" role="main">
The preceding view file contains the HTML for the head of a document. This is to say that this HTML is used throughout the book for every project, and it contains the HTML markup for everything from the opening
html
tag, opening and closinghead
tags, and the openingbody
tag.Create the
footer.php
file at/path/to/codeigniter/application/views/common/
and add the following code to it:</div> <!-- /container --> <link href="<?php echo base_url('bootstrap/css/bootstrap.min.css'); ?>" rel="stylesheet"> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script src="<?php echo base_url('bootstrap/js/bootstrap.min.js');?>"></script> <script src="<?php echo base_url('bootstrap/js/docs.min.js');?>"></script> </body> </html>
The preceding block of code contains the HTML markup for the footer view file used for every project throughout this book.
In each project throughout the book, we will create a specific language file containing specific language items that are relevant to that particular project. However, there are also common language elements that we won't repeat in each project (as there's no need); thus, we can have them here instead.
The language items mostly cover screen elements such as general navigation, general error and success messages, and CRUD actions (edit, delete, and so on).
With that in mind, let's go ahead and create the base language file that will serve as a template for the chapters in this book.
Create the en_admin_lang.php
file at /path/to/codeigniter/application/language/english/
and add the following code to it:
// Common form elements $lang['common_form_elements_next'] = "Next..."; $lang['common_form_elements_save'] = "Save..."; $lang['common_form_elements_cancel'] = "Cancel"; $lang['common_form_elements_go'] = "Go..."; $lang['common_form_elements_go_back'] = "Go back"; $lang['common_form_elements_submission_error'] = "There were errors with the form:"; $lang['common_form_elements_success_notifty'] = "Success:"; $lang['common_form_elements_error_notifty'] = "Error:"; $lang['common_form_elements_actions'] = "Actions"; $lang['common_form_elements_action_edit'] = "Edit"; $lang['common_form_elements_action_delete'] = "Delete"; $lang['common_form_elements_active'] = "Active"; $lang['common_form_elements_inactive'] = "Inactive"; $lang['common_form_elements_seccessful_change'] = "Your changes have been saved"; $lang['common_form_elements_seccessful_delete'] = "The item has been deleted"; $lang['common_form_elements_yes'] = "Yes"; $lang['common_form_elements_no'] = "No"; $lang['common_form_elements_to'] = "to"; $lang['common_form_elements_from'] = "from"; $lang['common_form_elements_history'] = "History";
The preceding language items are mostly for HTML forms and tables of data, such as the text for the Submit, Edit, Delete, and History buttons. Also included are general error or success messages. Feel free to add to them if you wish.
All projects in this book make use of the MY_Controller
file; this is the same for all projects.
Create the MY_Controller.php
file at /path/to/codeigniter/application/core/
and add the following code to it:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class MY_Controller extends CI_Controller { function __construct() { parent::__construct(); $this->load->helper('form'); $this->load->helper('url'); $this->load->helper('security'); $this->load->helper('language'); // Load language file $this->lang->load('en_admin', 'english'); } }
As you can see, we load helpers that are common to all projects, such as the form
helper and the language
helper, among others. The language file is also loaded here.
All the controllers in the project extend from this MY_Controller
file rather than the default CI_Controller
file.
We also are autoloading various resources such as support for database access and session management. We need to specify that we're using these resources.
Open the autoload.php
file from /path/to/codeigniter/application/config/
in your text editor and find the following line:
$autoload['libraries'] = array();
Replace this line with the following:
$autoload['libraries'] = array('database', 'session');
This will ensure that the resources that are required in order to access the database and to manage sessions are always with us.
Whatever you are programming, your two main priorities are security and maintainability; this is to say that your application should be as secure as is necessary and should be written in such a way that someone else can easily program and extend on what you're doing. I can't discuss maintainability—that's up to you—but I can give you guidance on CodeIgniter and security.
However, I should say that no security is 100 percent foolproof. Even banks and security agencies that spend hundreds of millions on systems still get hacked, so what chance do we have? Well, the best we can do is try to reduce the opportunity that someone might do something that could compromise our code or database.
You should move your system folder out of your web root. This is to make it as hard as possible for anything other than the web server to access. Take a look at the line in the main index.php
file:
$system_path = 'system';
Make sure that you amend the preceding line to this:
$system_path = '../system';
So, if we moved the system
folder out of the web root one level higher, we would use the../
convention, prepending it to system
.
Obviously you don't want to actually display error messages to the outside world. Over time, everyone will gain an understanding of the architecture of your site and where its weaknesses are, especially if you allow SQL errors to be displayed in a production environment.
For this reason, you should change the environment variable in the main index.php
file from development
to production
. This will suppress the reporting errors; 404 and 500 errors will still be caught and displayed normally but SQL errors and other similar errors will be suppressed.
For this, look at the following code in the index.php
file:
define('ENVIRONMENT', 'development');
/*
*---------------------------------------------------------------
* ERROR REPORTING
*---------------------------------------------------------------
*
* Different environments will require different levels of error reporting.
* By default development will show errors but testing and live will hide them.
*/
if (defined('ENVIRONMENT'))
{
switch (ENVIRONMENT)
{
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
break;
default:
exit('The application environment is not set correctly.');
}
}
Look at the line in bold (the first line). This line has set CodeIgniter to run in development mode; to change to anything else (specifically, a live mode), change the line in bold to the following:
define('ENVIRONMENT', 'production');
All errors will now be suppressed.
Query binding is a good idea; it makes your queries easier to read; queries that use the CodeIgniter binding are automatically escaped, leading to more secure queries. The syntax is simple; for example, consider the following query:
$query = "SELECT * FROM `users` WHERE user_email = ? AND user_level = ?";
Look at the end of the query; you can see that we use a question mark where we would normally use a variable; this is something that would normally look like this:
$query = "SELECT * FROM `users` WHERE user_email = $user_email AND user_level = $user_level";
How does CodeIgniter know what the question mark means, and how does CodeIgniter put the correct value in the query? Take a look at this second line:
$this->db->query($query, array($user_email, $user_level));
This is how it matches the value to the correct question mark. We use the $this->db->query()
CodeIgniter function, passing to it two arguments. The first is the $query
variable (containing the actual query), and the second is an array. Each position in the array matches the position of the question marks in the SQL string.