Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
CodeIgniter Web Application Blueprints
CodeIgniter Web Application Blueprints

CodeIgniter Web Application Blueprints: Develop full-featured dynamic web applications using the powerful CodeIgniter MVC framework

$28.99 $19.99
Book Jan 2015 330 pages 1st Edition
eBook
$28.99 $19.99
Print
$48.99
Subscription
$15.99 Monthly
eBook
$28.99 $19.99
Print
$48.99
Subscription
$15.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now
Table of content icon View table of contents Preview book icon Preview Book

CodeIgniter Web Application Blueprints

Chapter 1. Introduction and Shared Project Resources

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

Common resources


The common resources used in this book are discussed in upcoming sections.

Twitter Bootstrap

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.

Headers and footers

The menus will be different for individual projects. In the header file, we will include the code to display the menu, but the actual HTML contents for the menu will be included in each project's chapter. The footer file contains the closing HTML markup for each page.

Downloading CodeIgniter


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).

CodeIgniter on newer versions of PHP

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:

  1. Open the /path/to/codeigniter/system/core/common.php file and find the line 257.

  2. Find the following line:

    $_config[0] =& $config;
    with
    return $_config[0];
    return $_config[0] =& $config;
  3. Save the common.php file.

This will likely be permanently fixed in later releases of CodeIgniter, but for now, this is the fix.

Installing Twitter Bootstrap


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:

  1. 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:

  2. 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.

Removing index.php from the address bar


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:

  1. 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
      
  2. 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>

Installing and using Sparks


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:

    1. Create a folder called tools in the top level (root) or in your CodeIgniter directory.

    2. Go to http://getsparks.org/install.

    3. Go to the Normal Installation section and download the Sparks package.

    4. Unpack the download into the tools folder you created in step 1.

    5. Download the Loader class extension from http://getsparks.org/static/install/MY_Loader.php.txt.

    6. Rename the file MY_Loader.php.txt to MY_Loader.php and move it to the application/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!

Creating a shared header and footer view


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:

  1. 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 closing head tags, and the opening body tag.

  2. 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.

Common language items


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.

Creating the MY_Controller file


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.

Autoloading common system resources


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.

Security considerations


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.

Moving the system folder

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.

Error messages

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

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.

Summary


Now, you will discover that we are ready to start the book and are all set to tackle each chapter.

Remember that the code for each chapter is available at the Packt website, as is the SQL for each chapter; this will save you from having to type in all this stuff.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

What you will learn

Create a base application to form the building blocks to develop your own web applications Develop a user authorization system to enable user access and permit the resetting of passwords Build an application to upload photos along with their descriptions Develop a URL shortener to create a new URL and save it to the database Design a job board to create and list new jobs and also register users and agents Construct an application to assign time against task, by adding filters and graphics to data Expand an ecommerce website to provide online shopping facility to users

Product Details

Country selected

Publication date : Jan 21, 2015
Length 330 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781783287093
Category :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Jan 21, 2015
Length 330 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781783287093
Category :

Table of Contents

16 Chapters
CodeIgniter Web Application Blueprints Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
About the Reviewers Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
1. Introduction and Shared Project Resources Chevron down icon Chevron up icon
2. A URL Shortener Chevron down icon Chevron up icon
3. Discussion Forum Chevron down icon Chevron up icon
4. Creating a Photo-sharing Application Chevron down icon Chevron up icon
5. Creating a Newsletter Signup Chevron down icon Chevron up icon
6. Creating an Authentication System Chevron down icon Chevron up icon
7. Creating an E-Commerce Site Chevron down icon Chevron up icon
8. Creating a To-do List Chevron down icon Chevron up icon
9. Creating a Job Board Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Top Reviews
No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.