Codeigniter by Beni - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

index-1_1.jpg

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

www.PacktPub.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

http://PacktLib.PacktPub.com

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

Preface 1

Chapter 1: CodeIgniter Basics

5

Introduction 5

Downloading and installing CodeIgniter

5

Basic configuration options

6

Managing CodeIgniter on different environments

7

Managing database settings on different environments

8

Securing the system files

11

Removing index.php from the address bar using .htaccess

12

Installing and using Sparks

13

Chapter 2: User Management

15

Introduction 15

Viewing users

18

Creating users

21

Editing users

24

Deleting users

28

Generating passwords with CodeIgniter

31

Generating passwords with CodeIgniter – the bare bones

41

Forgot password? – resetting passwords with CodeIgniter

43

Chapter 3: Creating E-commerce Features

51

Introduction 51

Amending configuration settings to run sessions in a database

51

Creating a basic cart

54

Adding and searching by product categories

59

Saving the cart to the database

63

Table of Contents

Chapter 4: Email, HTML Table, and Text Libraries

69

Introduction

69

Sending plain e-mails with CodeIgniter Email

70

Sending HTML e-mails with CodeIgniter Email

72

Sending attachments with CodeIgniter Email

74

Sending bulk e-mails with CodeIgniter Email

76

Using an HTML table with DataTable

81

Using an HTML table with DataTable and a database

86

Using word_limiter() for table output

90

Using word_censor() for cleaning input

94

Chapter 5: Managing Data In and Out

99

Introduction 100

Sending different data to multiple views

100

Validating user input

103

Preparing user input

110

Sticky form elements in CodeIgniter

110

Displaying errors next to form items

112

Reading files from the filesystem

113

Writing files to the filesystem

116

Creating and downloading ZIP files

117

Uploading files with CodeIgniter

118

Creating and using validation callbacks

122

Using the language class

123

Confirming cookie acceptance from the user

126

Chapter 6: Working with Databases

133

Introduction 134

Configuring CodeIgniter for databases

134

Connecting to multiple databases

135

Active Record – create (insert)

140

Active Record – read (select)

144

Active Record – update

146

ActiveRecord – delete

148

Looping through the database results

150

Counting the number of returned results with num_rows()

152

Counting the number of returned results with count_all_results()

153

Query binding

154

Finding the last insert id

155

Finding the number of affected rows

156

Finding the last database query

156

ii

Table of Contents

Using CodeIgniter database migrations

157

Moving to the current version with current()

161

Rolling back/stepping forward with version()

162

Generating an XML from a database result

163

Generating a CSV from a database result

165

Chapter 7: Creating a Secure User Environment

169

Introduction

169

Escaping user input

169

Preventing cross-site request forgery

171

Escaping data – for a database

173

Using HTTPS with CodeIgniter

178

Chapter 8: Calendaring, Right Place, and Right Time

183

Introduction 183

Building a CodeIgniter Calendar helper with database results

183

Building an appointment manager with Calendar Library

190

Creating a helper to work with a person's date of birth

202

Working with fuzzy dates in CodeIgniter

205

Chapter 9: Extending the Core

211

Introduction 211

Using CodeIgniter Sparks

212

Creating PDFs with the DOMPDF Spark

213

Creating Hooks in CodeIgniter

216

Clearing dead sessions from the database

219

Extending your controllers

221

Uploading a file with FTP

223

Creating libraries and giving them access to CodeIgniter resources

226

Making your own configuration files and using the settings

231

Using the language class – switching language on the go

232

Chapter 10: Working with Images

241

Introduction 241

Installing ImageMagick on MAC with Cactuslab

241

Uploading images with CodeIgniter

242

Generating thumbnails – resizing

244

Rotating images

247

Cropping images

249

Adding watermarks with text

252

Adding watermarks with image overlays

255

Submitting a form with CodeIgniter CAPTCHA

257

iii

Table of Contents

Chapter 11: SEO, Caching, and Logging

265

Introduction

265

Using SEO-friendly URLs in CodeIgniter

265

Using CodeIgniter caching

268

Logging errors with CodeIgniter

272

Benchmarking your application

277

Index 283

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