CodeIgniter 2
Cookbook
Over 80 recipes to help you create CodeIgniter-powered
applications and solve common coding problems
Rob Foster
BIRMINGHAM - MUMBAI
CodeIgniter 2 Cookbook
Copyright © 2013 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
First published: December 2013
Production Reference: 1061213
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78216-230-8
www.packtpub.com
Cover Image by Raju Menon (raju6712in@gmail.com)
Credits
Author
Project Coordinator
Rob Foster
Navu Dhillon
Reviewers
Proofreaders
Harpreet Singh Bhatia
Ameesha Green
Marion Newlevant
Linda Morris
Ahmed Samy
John Skoumbourdis
Indexer
Monica Ajmera Mehta
Acquisition Editor
Joanne Fitzpatrick
Graphics
Rob Parsons
Lead Technical Editor
Abhinash Sahu
Neeshma Ramakrishnan
Production Coordinator
Technical Editors
Kyle Albuquerque
Kapil Hemnani
Gauri Dasgupta
Cover Work
Kyle Albuquerque
Jalasha D'costa
Dipika Gaonkar
Monica John
Edwin Moses
Faisal Siddique
Copy Editors
Brandt D'Mello
Gladson Monteiro
Laxmi Subramanian
About the Author
Rob Foster has been working in web development for almost 10 years, focusing on the LAMP stack (although currently rocking a MAC), and has been developing with CodeIgniter for over three years. He has worked in IT for various sectors including public health, charity, new media, and even the gaming industry.
I would like to thank Lucy for all the missed weekends I spent working on the book (at least you got to 62 on Skyrim), Rob Parsons for doing a great job on the images in the book. Thanks to Mum and Dad, Peter and family, Richard (good to have you back again), friends, and family.
About the Reviewers
Harpreet Singh Bhatia is a freelance developer who believes that coding is as much art as it is science, because it not only involve a strong, logical thinking with a care for system resources, but also gives the coder the ability to express himself in order to ensure a smooth flow, making code.
He has a Master's degree in IT and a diploma in Software Engineering from NIIT.
He specializes in a wide array of technologies. He is proficient in web application languages, tools, and frameworks including PHP, JavaScript, jQuery, Ajax, CodeIgniter, MySQL, WordPress, CSS3, and HTML5; the Unix environment being his forte.
He has worked in multiple capacities in the IT field. He started off as a teacher/instructor in APTECH. He then switched to development and has served companies such as Screwdriver Infotainment, Kent RO, Design Emporia, Syc Creatives (Malaysia), Multi Design (Norway), and many more. He is also a proud member of “The Group Ry” (Finland).
He has had an enriching experience in software and IT infrastructure development, spanning a wide IT spectrum. This includes web development, application designing, system installation and configuration, and so on.
I would like to thank my father for provoking me to review this book. I would also like to thank the publisher for reaching out to me for this work.
Marion Newlevant started programming at the tail end of the punch card era, and has been doing it ever since. She is a big fan of well-organized code, and started working with CodeIgniter in 2010.
Ahmed Samy is a PHP web developer who is currently working for Edfa3ly.com, a superstar e-commerce start-up in Egypt that considers technology as a key player for success.
He has mainly worked with CodeIgniter, Symfony2, Fuel, NoSQL MongoDB, and has recently worked implementing more scalable systems using SOA approaches.
He’s also the founder of HypeLabs, a small business that delivers web/mobile app services and is currently in the planning stage of a new start-up idea.
He believes that sharing knowledge with other people is one of the keys to success.
John Skoumbourdis (known as Johnny) is a senior web developer who loves coding.
He is always trying to maximize and improve his skills by learning new things in a challenging environment. His mission is to create beautiful and professional websites and help other people to do so by sharing his knowledge. He is currently developing three really famous libraries in CodeIgniter; they are:
f
Grocery CRUD (http://www.grocerycrud.com)
f
Image CRUD (http://www.grocerycrud.com/image-crud)
f
CodeIgniter Simplicity (http://www.grocerycrud.com/codeigniter-
simplicity)
If you want to know more about him, you can visit his personal blog at http://www.web-and-development.com/.
Support files, eBooks, discount offers and more
You might want to visit www.PacktPub.com for support files and downloads related to your book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print
book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
service@packtpub.com for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
TM
Do you need instant solutions to your IT questions? PacktLib is Packt’s online digital book library. Here, you can access, read and search across Packt’s entire library of books.
Why Subscribe?
f
Fully searchable across every book published by Packt
f
Copy and paste, print and bookmark content
f
On demand and accessible via web browser
Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.
Table of Contents
Chapter 1: CodeIgniter Basics
Downloading and installing CodeIgniter
Managing CodeIgniter on different environments
Managing database settings on different environments
Removing index.php from the address bar using .htaccess
Chapter 2: User Management
Generating passwords with CodeIgniter
Generating passwords with CodeIgniter – the bare bones
Forgot password? – resetting passwords with CodeIgniter
Chapter 3: Creating E-commerce Features
Amending configuration settings to run sessions in a database
Adding and searching by product categories
Saving the cart to the database
Table of Contents
Chapter 4: Email, HTML Table, and Text Libraries
Sending plain e-mails with CodeIgniter Email
Sending HTML e-mails with CodeIgniter Email
Sending attachments with CodeIgniter Email
Sending bulk e-mails with CodeIgniter Email
Using an HTML table with DataTable
Using an HTML table with DataTable and a database
Using word_limiter() for table output
Using word_censor() for cleaning input
Chapter 5: Managing Data In and Out
Sending different data to multiple views
Sticky form elements in CodeIgniter
Displaying errors next to form items
Reading files from the filesystem
Writing files to the filesystem
Creating and downloading ZIP files
Uploading files with CodeIgniter
Creating and using validation callbacks
Confirming cookie acceptance from the user
Chapter 6: Working with Databases
Configuring CodeIgniter for databases
Connecting to multiple databases
Active Record – create (insert)
Looping through the database results
Counting the number of returned results with num_rows()
Counting the number of returned results with count_all_results()
Finding the number of affected rows
Finding the last database query
ii
Table of Contents
Using CodeIgniter database migrations
Moving to the current version with current()
Rolling back/stepping forward with version()
Generating an XML from a database result
Generating a CSV from a database result
Chapter 7: Creating a Secure User Environment
Preventing cross-site request forgery
Escaping data – for a database
Chapter 8: Calendaring, Right Place, and Right Time
Building a CodeIgniter Calendar helper with database results
Building an appointment manager with Calendar Library
Creating a helper to work with a person's date of birth
Working with fuzzy dates in CodeIgniter
Chapter 9: Extending the Core
Creating PDFs with the DOMPDF Spark
Clearing dead sessions from the database
Creating libraries and giving them access to CodeIgniter resources
Making your own configuration files and using the settings
Using the language class – switching language on the go
Chapter 10: Working with Images
Installing ImageMagick on MAC with Cactuslab
Uploading images with CodeIgniter
Generating thumbnails – resizing
Adding watermarks with image overlays
Submitting a form with CodeIgniter CAPTCHA
iii
Table of Contents
Chapter 11: SEO, Caching, and Logging
Using SEO-friendly URLs in CodeIgniter
Logging errors with CodeIgniter
iv
Preface
CodeIgniter 2 Cookbook offers many easy-to-use, easy-to-integrate, and easy-to-adapt recipes using HTTPS, image manipulation, cookie acceptance, form validation, and so on. It is a great resource for 2 AM problems.
What this book covers
Chapter 1, CodeIgniter Basics, takes you through CodeIgniter's download and installation, basic configuration, and so on.
Chapter 2, User Management, focuses on building a basic CRUD interface for managing users.
Chapter 3, Creating E-commerce Features, explores the use of the CodeIgniter Cart class to create a simple storefront, allowing a customer to add items to the cart and checkout.
Chapter 4, Email, HTML Table, and Text Libraries, focuses on sending e-mails using the CodeIgniter Email library, creating interactive tables, and using a few handy HTML functions.
Chapter 5, Managing Data In and Out, deals with form validation, writing files to disk, confirming cookie acceptance from the user, and so on.
Chapter 6, Working with Databases, covers the usage of basic Active Record functions, exporting data from a database query binding, and most of what you might need to work with databases.
Chapter 7, Creating a Secure User Environment, covers escaping user input, switching to and from HTTPS in CodeIgniter, and so on.
Chapter 8, Calendaring, Right Place, and Right Time, deals with creating an interactive calendar that you can add appointments to using fuzzy dates and calculating a person's date of birth (for age verification).
Preface
Chapter 9, Extending the Core, focuses on using the language class and switching languages on the go, creating hooks, uploading files with FTP, and extending your controllers with MY_Controller.
Chapter 10, Working with Images, deals with using the CodeIgniter image manipulation library to crop, rotate, and add watermarks to images and adding CAPTCHA validation to forms.
Chapter 11, SEO, Caching, and Logging, deals with caching data from a database, using the CodeIgniter routing methods to alter and amend how URLs are displayed in a browser's address bar, and logging errors and other activities throughout your application.
What you need for this book
You will require the following software:
f
An *AMP environment (LAMP, MAMP, WAMP, and so on)
f
A copy of the CodeIgniter framework
Who this book is for
CodeIgniter is an easy-to-pick-up framework written in PHP; so, familiarity with PHP and CodeIgniter is advantageous. But, having no experience with CodeIgniter shouldn't be a road block to read the book either. The best thing to do (if you're unsure) is to buy it and just jump in. Having said that, if you are familiar with CodeIgniter, this book can provide immediate sold snippets and recipes you can use for all sorts of day-to-day, CodeIgniter-related tasks.
Conventions
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: " The public function index() function redirects us to the function public function send_mail()."
A block of code is set as follows:
$this->email->from('from@domain.com', 'Your Name');
$this->email->to('to@domain.com');
$this->email->subject('This is a text email');
$this->email->message('And this is some content for the text email.');
2
Preface
When we wish to draw your attention to a particular part of a code block, the relevant lines or items a