Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Discover millions of ebooks, audiobooks, and so much more with a free trial

From $11.99/month after trial. Cancel anytime.

CodeIgniter 1.7 Professional Development
CodeIgniter 1.7 Professional Development
CodeIgniter 1.7 Professional Development
Ebook757 pages3 hours

CodeIgniter 1.7 Professional Development

Rating: 2 out of 5 stars

2/5

()

Read preview

About this ebook

In Detail

CodeIgniter is an open source PHP framework with a small footprint and exceptional performance. It gives you a rich set of libraries for common tasks, with a simple interface to access them. There are several unexplored aspects of CodeIgniter that can help developers build applications more easily and quickly. In this book, you will learn the intricacies of the framework and explore some of its hidden gems.

If you want to get the most out of CodeIgniter, this book is for you. It teaches you what you need to know to use CodeIgniter on a daily basis. You will create mini-applications that teach a specific technique and let you build on top of the base.

This book will take you through developing applications with CodeIgniter. You will learn how to make your CodeIgniter application more secure than a default installation, how to build large-scale applications and web services, how to release code to the community, and much more. You will be able to authenticate users, validate forms, and also build libraries to complete different tasks and functions.

The book starts off introducing the framework and how to install it on your web server or a local machine. You are introduced to the Model-View-Controller design pattern and how it will affect your development. Some important parts of the CodeIgniter Style Guide are included to keep CodeIgniter development as standardized as possible; this helps greatly when working as part of a team or taking on an old CodeIgniter project. You will quickly move on to how CodeIgniter URLs work and learn about CodeIgniter-specific files such as helpers and plugins. By the time you finish this book, you will be able to create a CodeIgniter application of any size with confidence, ease, and speed.

This guide will enable you to become well-versed with CodeIgniter through practical applications using the tools and techniques used by many seasoned CodeIgniter developers.

Approach

This book is a practical guide that takes you through a number of techniques. Each chapter builds upon knowledge from the previous chapter. Step-by-step instructions with examples and illustrative screenshots ensure that you gain a firm grasp of the topic being explained.

Who this book is for

This book is written for advanced PHP developers with a good working knowledge of Object Oriented Programming techniques who are comfortable with developing applications and wish to use CodeIgniter to make their development easier, quicker, and more fun. Basic knowledge of CodeIgniter will be helpful. This book will suit developers who fall into three categories:

  • Professional Developers - employees of a software house or organization with in-house software development
  • Freelance Developers - solo developers working in the industry on their own
  • Just-for-fun Developers - people working with PHP building web applications is their spare time for fun
LanguageEnglish
Release dateApr 26, 2010
ISBN9781849510912
CodeIgniter 1.7 Professional Development
Author

Adam Griffiths

Adam Griffiths is a student and freelance CodeIgniter Developer based in the United Kingdom. He has five years web development experience, the last two being largely influenced by CodeIgniter. He has worked on many websites, both large and small, from small blogs to large multi-national companies. He is well versed in development techniques and how to squeeze that little bit more from an application. He has also made a number of contributions to the CodeIgniter Community, most notably The Authentication Library, a very simple-to-use but full-featured Authentication Library for CodeIgniter. When CodeIgniter and PHP aren't spiralling around his head, Adam enjoys practising card and mentalist tricks, mainly sleight of hand and card handling. He has performed at local and formal functions for hundreds of people. He is also a guitar player and enjoys playing acoustically at pubs and small gigs. Moving back towards computing, he has a deep interest in Cryptography. He loves finding patterns in data and loves using pen and paper to decipher any cipher text he may find around the web.

Related to CodeIgniter 1.7 Professional Development

Related ebooks

Information Technology For You

View More

Related articles

Reviews for CodeIgniter 1.7 Professional Development

Rating: 2 out of 5 stars
2/5

2 ratings1 review

What did you think?

Tap to rate

Review must be at least 10 words

  • Rating: 2 out of 5 stars
    2/5
    Much of this book's material can be found just as easily and for free in the documentation that comes with CodeIgniter. Some of the material in the second half of the book was useful to me, though it was offset to a large extent by some iffy material, including what to me appeared to be some rather poor implementation of OOP concepts. This book may be useful to intermediate PHP developers who are brand new to CodeIgniter, but I cannot recommend it to anyone with more experience with both.

Book preview

CodeIgniter 1.7 Professional Development - Adam Griffiths

(missing alt)

Table of Contents

CodeIgniter 1.7 Professional Development

Credits

About the Author

About the Reviewers

Preface

What this book covers

Who this book is for

Conventions

Reader feedback

Customer support

Errata

Piracy

Questions

1. Getting Started with CodeIgniter

Upgrading from older versions of CodeIgniter

Downloading and installing CodeIgniter

Getting the CodeIgniter files

Introducing Model View Controller (MVC)

Controllers: The business logic

Defining a default Controller

Remapping function calls

Models: Data abstraction layer

Loading a Model

Connecting to your database automatically

Views: Your template files

Loading a view

Loading multiple views

Adding dynamic data

Creating loops

Returning views as data

Autoloading resources

Formatting your code—PHP Style Guide

PHP closing tag

Incorrect

Correct

Class and method naming

Incorrect

Correct

Incorrect

Correct

Variable names

Incorrect

Correct

Commenting

Poor

Good

Use of TRUE, FALSE, and NULL

Incorrect

Correct

Short opening tags

Incorrect

Correct

One statement per line

Incorrect

Correct

CodeIgniter URLs

Removing the index.php file

Adding a URL Suffix

CodeIgniter specific files

Helpers

Loading a helper

Loading multiple helpers

Using a helper

Extending Helpers

Plugins

Loading a plugin

Loading multiple plugins

Using a plugin

Libraries

Creating your own libraries

Using CodeIgniter resources within your library

Using your class

Extending core libraries

Loading your extended library

Replacing core libraries

Summary

2. Learning the Libraries

What is a library?

What do libraries do?

Benchmarking Class

Setting a benchmark

Setting multiple benchmarks

Profiling your benchmarks

Making use of the Profiler Class

Display total execution time

Display memory consumption

Input and Security Class

XSS filtering

Filtering a single item

Automatic filtering

Filtering images

Retrieving POST data

Retrieving GET data

Retrieving GET and POST data

Retrieving COOKIE data

Retrieving SERVER data

IP Addresses

Retrieving a user agent

Email Class

Send an e-mail

Build a contact form

Our contact form

Checking if the form has been submitted

Checking the values of the form

Validate the e-mail

Using the XSS filter

Send the e-mail

Using the Email Class

Using the Email Helper

Batch e-mail processing

File Uploading Class

Create the Upload Views

Create the Upload Controller

Our initial controller

Specify the allowed file types and maximum file size

Uploading the file

Image Manipulation Library

Initializing the library

Creating a thumbnail

Cropping an image

Rotating an image

Clearing values in loops

Pagination Class

Example

Customizing the pagination

Customize the First link

Customize the Last link

Customize the Next link

Customize the Previous link

Customize the Current Page link

Customize the Digit link

Session Class

Initializing the Session Class

Autoload the Session Class

Manually load the Session Class

How do CodeIgniter sessions work?

What is stored in a session?

Adding session data

Retrieving session data

Removing session data

Removing a single session item

Removing multiple session items

Destroying a session

Flash data

Add flashdata

Read flashdata

Keep flashdata

Using a session database

Unit testing a class

Initializing the class

Running tests

Generating reports

Strict mode

Enabling or disabling unit testing

Create a template

Summary

3. Form Validation and Database Interaction

Why should I validate my forms?

Using the Form Validation Library

The form validation process

The user's process

The development process

Contact form

Loading the assets

Setting the rules

List of validation rules

Prepping data

The rules

Check the validation process

Sending the email

Final controller code

Changes to the form view

Re-populating field values

Showing individual errors

Final form view

Changing the error delimiters

Changing delimiters globally

Changing delimiters individually

Saving sets of validation rules to a config file

Creating sets of rules

Calling a specific set of rules

Associating a rule group with a controller

Using callbacks

Include the callback in the rules

Creating the callback

Create the function

Load the database library

Performing the database query

Adding a condition

Show a success page

Database interaction

Loading the library

Performing simple queries

Returning values

Returning a result object

Returning a result array

Returning a row object

Returning a row array

Result helper functions

Number of rows returned

Number of fields returned

Free result

Active Record

Selecting data

$this->db->get();

$this->db->get_where();

$this->db->select();

$this->db->from();

$this->db->join();

$this->db->where();

Single key or value method

Multiple key or value method

Custom key or value method

Associative array method

Custom string

$this->db->like();

Single key or value method

Multiple key or value method

Associative array method

$this->db->group_by();

$this->db->order_by();

$this->db->limit();

Inserting data

$this->db->insert();

$this->db->set();

Updating data

$this->db->update();

Deleting data

$this->db->delete();

$this->db->empty_table();

$this->db->truncate();

Active Record caching

$this->db->start_cache();

$this->db->stop_cache();

$this->db->flush_cache();

Method chaining

Manipulating databases with Database Forge

Loading the Forge class

Creating a database

Dropping a database

Adding fields

Creating a table

Dropping a table

Renaming a table

Modifying a table

$this->dbforge->add_column();

$this->dbforge->drop_column();

$this->dbforge->modify_column();

Summary

4. User Authentication 1

Defining our goals

Our goals

Creating and connecting to the database

Front end code

Index function

Details view

Dashboard function

Dashboard view

Login function

Form validation

Password check

Running the validation

Full login code

Login view

Success view

Register function

Form validation

User exists check

Email exists check

Running the validation

Full register code

Full controller code

Register view

Error view

Logout function

Logout view

Model code

Model constructor

Create function

Login function

Logged in check function

Full model code

Addressing some issues

The Authentication Library

Summary

5. User Authentication 2

Using Twitter oAuth

How oAuth works

Registering a Twitter application

Downloading the oAuth library

Library base class

Controller base class

Library constructor

Requesting user tokens

HTTP function

Parse function

Controller index function

get_authorize_URL function

Main view file

Change your callback URL

Creating the access function

The view file

Getting access tokens

get_access_tokens()

parse_access()

Logging out

Debug function

Final library code

Final controller code

Using Facebook Connect

Registering a Facebook application

Download the Client library

Our CodeIgniter Wrapper

Base class

Class constructor

_session();

Final library code

The Controller

The View file

Summary

6. Application Security

CodeIgniter's defenses

URI security

Why does CodeIgniter use URIs?

Why does CodeIgniter restrict URI characters?

Global data

Best practices

Filtering data

Validation

Escaping data

Strong password policies

Example Form Validation Library rules

Storing passwords securely

Storing hashes

Hashing a password using sha1

The sha1() function

The $this->encrypt->sha1() function

Load the library

Hash the password

Static salting

Simple salts

Complex salts

Split at second character

Split the password in the middle

Dynamic salting

Simple dynamic salts

Complex dynamic salts

Encrypting passwords

Setting an encryption key

Message length

Loading the class

Encoding passwords

Decoding passwords

Set mcrypt cipher

Database security

Escape queries

The $this->db->escape() function

The $this->db->escape_str() function

The $this->db->escape_like_str() function

Query bindings

Limiting account access

Cross-site scripting (XSS)

Changing the default file structure

Staying up-to-date

Summary

7. Building a Large-Scale Application

Running benchmarks

Why run benchmarks?

Where should I use benchmarks?

Types of bottlenecks

Database

Identifying a database bottleneck

Rectifying a database bottleneck

Code

Identifying a code bottleneck

Rectifying a code bottleneck

API

Identifying an API bottleneck

Rectifying an API bottleneck

Bandwidth

Identifying a bandwidth bottleneck

Rectifying a database bottleneck

Static

Identifying a static bottleneck

Rectifying a static bottleneck

Caching

How does it work?

How long should I cache pages for?

Using caching

Optimize SQL queries

Query caching

To cache or not to cache?

How query caching works

Managing cache files

Using query caching

Deleting cache files

Deleting all cache files

Limit results

LIMIT clause

Only select what you need

Avoid disk activity

Memcache example

Memcache CodeIgniter library

Constructor

Data functions

Maintenance functions

Full library code

Using the library

Run multiple application instances

Advantages

Disadvantages

Summary

8. Web Services

What is a web service?

Types of web service

Remote procedure call

Representational State Transfer

RESTful web service

Defining the resource

How it will work

Creating our files

Setting up the database

REST library

Base class

Performing a GET request

Performing a PUT request

Performing a POST request

Performing a DELETE request

Response function

The format XML function

The format JSON function

Final library code

Rest Controller

Base class

The _remap() function

Server Controller

Base class

The post_get() function

The post_put() function

The post_delete() function

The post_post() function

Final server controller code

Post Model

Base class

The get_post() function

The update_post() function

The create_post() function

The delete_post() function

Final post model code

Create a new post

Update a post

Delete a post

Get a blog post

Summary

9. Extending CodeIgniter

Hooks

Hook points

pre_system

pre_controller

post_controller_constructor

post_controller

display_override

cache_override

scaffolding_override

post_system

Our hook

Enable hooks

Define a hook

Our hook

Extended controllers

Admin controller

Extended libraries

The library

Base class

userdata()

set_userdata()

unset_userdata()

Full library code

Custom libraries

The features

The library

The controller

Helpers

CodeIgniter's hidden gems

doctype()

Array helper

element()

random_element()

Inflector helper

singular()

plural()

camelize()

underscore()

humanize()

highlight_code()

directory_map()

Summary

10. Developing and Releasing Code to the Community

Find a need in the community (or fill your own need)

Search for existing solutions

Use the solutions

Reinvent the wheel

List the problems of these solutions

Create a plan

List the features

Prioritize the features

Writing the library

Review your code

Comments

Fix the problems

Write a user guide

Explain the function

Show the user how to use the function

Let the user know of any shortcomings

Use the style sheet given in the CodeIgniter User Guide

Release options

Forum post

Post on your website

GitHub

Handling database tables

Include a .sql file

Include an install file

Supporting the code

Update regularly

Listen to the users

Accept contributions

Communicate regularly

Don't give a release date

Keep testing

Archive old versions

Use the wiki

Summary

Index

CodeIgniter 1.7 Professional Development

Adam Griffith


CodeIgniter 1.7 Professional Development

Copyright © 2010 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: April 2010

Production Reference: 1190410

Published by Packt Publishing Ltd.

32 Lincoln Road

Olton

Birmingham, B27 6PA, UK.

ISBN 978-1-849510-90-5

www.packtpub.com

Cover Image by Filippo (<filosarti@tiscali.it>)

Credits

Author

Adam Griffiths

Reviewers

Jose Argudo

Saidur Rahman

Acquisition Editor

Dilip Venkatesh

Development Editor

Dilip Venkatesh

Technical Editor

Aaron Rosario

Indexer

Monica Ajmera Mehta

Editorial Team Leader

Akshara Aware

Project Team Leader

Lata Basantani

Project Coordinator

Joel Goveya

Proofreader

Dirk Manuel

Production Coordinator

Shantanu Zagade

Cover Work

Shantanu Zagade

About the Author

Adam Griffiths is a student and freelance CodeIgniter Developer based in the United Kingdom. He has five years of web development experience, the last two being largely influenced by CodeIgniter. He has worked on many websites, both large and small, from small blogs to large websites for multi-national corporate companies. He is well versed in development techniques and how to squeeze that little bit more from an application. He has also made a number of contributions to the CodeIgniter Community, most notably The Authentication Library, a very simple to use but full-featured Authentication Library for CodeIgniter.

When CodeIgniter and PHP aren't spiralling around his head, Adam enjoys practising card and mentalism tricks, mainly sleight of hand and card handling tricks. He has performed at local and formal functions for hundreds of people. He is also a guitar player and enjoys playing acoustically at pubs and small gigs. Moving back towards computing, he has a deep interest in Cryptography. He loves finding patterns in data and loves using pen and paper to decipher any cipher text he may find around the web. Find out more and read his blog at http://www.adamgriffiths.co.uk.

I would like to thank my parents for encouraging me to better myself. If it weren't for them I may not have written this book. I would also like to thank my friends for letting me bounce ideas off of them and develop these ideas. I've wanted to write a book for a while now, so a big thank you goes to Packt Publishing for giving me this opportunity; and to everybody involved in reviewing, editing, and managing the book as a whole.

To the readers—Thank you for purchasing this book. It means a great deal to me that you will be reading the content that I spent a lot of time on, and you will hopefully learn a lot from it.

About the Reviewers

Jose Argudo is a web developer from Valencia, Spain. After finishing his studies he started working for a web design company. Six years later, he decided to start working as a freelancer.

Now that some years have passed as a freelancer, he thinks it's the best decision he has ever taken—a decision that let him work with the tools he likes, such as Joomla!, Codeigniter, Cakephp, Jquery, and other well-known open source technologies.

His desire to learn and share his knowledge has led him to be a regular reviewer of books from Packt, such as Joomla! With Flash, Joomla! 1.5 SEO, Magento Theme Design or Symfony 1.3 web application development.

Recently he has even published his own book, Codeigniter 1.7, which you can also find at Packt's site. If you work with PHP, take a look at it!

If you want to know more about him, you can check out his site at www.joseargudo.com

To my girlfriend and to my brother, I wish them the best.

Saidur Rahman Bijon is an open source enthusiast from Bangladesh. He graduated in computer science in from BRAC university and has been developing web applications for over four years. In this time, he has developed ecommerce, web 2.0, social networking, and microblogging applications. He shares his knowledge and ideas at http://saidur.wordpress.com.

He started his career by developing a large scale application for the Bangladesh Navy. Since then, he has worked mainly for Japanese and USA based outsourcing companies, where he has built applications in CodeIgniter. Currently, he is working for a USA based company, Blueliner Bangla (http://www.bluelinerny.com/) as a senior software engineer.

I'd like to thank Packt for giving me the opportunity to review this book.

I enjoyed it thoroughly.

I'm really thankful for my family, friends, and colleagues for their help and support.

I dedicate this book to my family.

Preface

This book takes you beyond the CodeIgniter user guide and into more advanced subjects that you need to know if you plan to use CodeIgniter on a daily basis. The book will teach you how to build libraries in order to complete different tasks and functions. You will create mini-applications each of which teaches a specific technique and builds on top of the CodeIgniter base. By the time that you finish this book you will be able to create a CodeIgniter application of any size with confidence, ease, and speed.

What this book covers

Chapter 1, Getting Started with CodeIgniter—This chapter guides you from installing CodeIgniter to learning about its URL structure, the MVC design pattern, helpers, plugins, and extending and replacing libraries.

Chapter 2, Learning the Libraries—You are taken through a number of the core CodeIgniter libraries, being introduced to each library, what it does and how you go about using it. Some libraries work together, and if this is the case, then this chapter explains how they can be used together.

Chapter 3, Form Validation and Database Interaction—Form validation is a task that some users find difficult. This chapter focuses on teaching you the correct way to validate your forms, by using the Form Validation library. You will also cover the Database library and Database Forge, a way to easily manage database tables.

Chapter 4, User Authentication 1—The first User Authentication chapter focuses on building your own authentication system. We build a model that handles the registration and logging in of users. We also include a function to check whether a user is logged in or not.

Chapter 5, User Authentication 2—The second and final User Authentication chapter focuses solely on user log-in in through Twitter oAuth and Facebook Connect. For each example the CodeIgniter code is explained, as well as how both company's APIs work, and to some extent how each differs from the other.

Chapter 6, Application Security—This chapter discusses how CodeIgniter is secure by design, for example, disallowing certain characters in the URI strings. We also go over what you can do to make your CodeIgniter application more secure than a default installation.

Chapter 7, Building a Large-Scale Application—This chapter takes you through some of the techniques that you can use to make your CodeIgniter application scalable. You learn about identifying bottlenecks via benchmarking results, caching, using better PHP functions, optimizing SQL queries, and using memcache and multiple application instances.

Chapter 8, Web Services—This chapter builds an example web service by using the REST principle. This includes a simple client library that issues requests, and a server library that deals with requests and responds as appropriate.

Chapter 9, Extending CodeIgniter—This chapter covers everything you need to know about extending CodeIgniter's default functionality without hacking at the core files. This is very useful, especially when it is time to upgrade to the newest version of CodeIgniter.

Chapter 10, Developing and Releasing Code to the Community—In this chapter you will learn how to release code to the community, gain exposure for your released code, and how to properly maintain the code and give good support to those using your code.

Who this book is for

This book is written for advanced PHP developers with a good working knowledge of Object Oriented Programming techniques who are comfortable with developing applications and wish to use CodeIgniter to make their development easier, quicker and more fun. Basic knowledge of CodeIgniter will be helpful. This book will suit developers who fall into three categories:

Professional Developers—Employees of a software house or other type of development company

Freelance Developers—A sole developer working in the industry on their own

Just for fun Developer—A person using PHP to build web applications is their spare time for fun

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 are shown as follows: We can include other contexts through the use of the include directive.

A block of code is set as follows:

[default]

exten => s,1,Dial(Zap/1|30)

exten => s,2,Voicemail(u100)

exten => s,102,Voicemail(b100)

exten => i,1,Voicemail(s0)

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

[default]

exten => s,1,Dial(Zap/1|30)

exten => s,2,Voicemail(u100)

exten => s,102,Voicemail(b100)

 

exten => i,1,Voicemail(s0)

Any command-line input or output is written as follows:

# cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample     /etc/asterisk/cdr_mysql.conf

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: clicking on the Next button moves you to the next screen.

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail

Enjoying the preview?
Page 1 of 1