CodeIgniter 1.7
By David Upton and Jose Argudo Blanco
()
About this ebook
CodeIgniter (CI) is a powerful open-source PHP framework with a very small footprint, built for PHP coders who need a simple and elegant toolkit to create full-featured web applications. CodeIgniter is an MVC framework, similar in some ways to the Rails framework for Ruby, and is designed to enable, not overwhelm.
This book explains how to work with CodeIgniter in a clear logical way. It is not a detailed guide to the syntax of CodeIgniter, but makes an ideal complement to the existing online CodeIgniter user guide, helping you grasp the bigger picture and bringing together many ideas to get your application development started as smoothly as possible.
This book will start you from the basics, installing CodeIgniter, understanding its structure and the MVC pattern. You will also learn how to use some of the most important CodeIgniter libraries and helpers, upload it to a shared server, and take care of the most common problems. If you are new to CodeIgniter, this book will guide you from bottom to top. If you are an experienced developer or already know about CodeIgniter, here you will find ideas and code examples to compare to your own.
Improve your PHP coding productivity with this guide to the powerful and popular CodeIgniter framework.
ApproachThis book takes a step-by-step approach, presenting the main features of CodeIgniter in a systematic way and explaining them clearly. It is packed with examples, ideas, and screenshots to help you master this great framework. The code examples are very practical so you can even use them in your own projects. By following this book, you can use CodeIgniter in the best possible way and maximize your learning.
Who this book is forThis book is for developers who are new to CodeIgniter. Basic skills in PHP and MySQL are required, but only rudimentary object-oriented knowledge is needed.
If you're looking for a better way to develop PHP applications, or want to find out more about the CodeIgniter framework as a viable option for one of your own projects, this book will help you.
David Upton
David Upton is a director of a specialized management consultancy company, based in London but working around the world. His clients include some of the world's largest companies. He is increasingly interested in web-enabling his work, and seeking to turn ideas into robust professional applications by the simplest and easiest route. He has so far written applications for two major companies in the UK. His other interests include simulation, on which he writes a weblog which takes up far too much of his time, and thinking.
Related to CodeIgniter 1.7
Related ebooks
ASP.NET 8 Best Practices: Explore techniques, patterns, and practices to develop effective large-scale .NET web apps Rating: 0 out of 5 stars0 ratingsTools and Skills for .NET 8: Get the career you want with good practices and patterns to design, debug, and test your solutions Rating: 0 out of 5 stars0 ratingsBuilding Websites with VB.NET and DotNetNuke 4 Rating: 1 out of 5 stars1/5Clojure Web Development Essentials Rating: 0 out of 5 stars0 ratingsNode Web Development, Second Edition Rating: 0 out of 5 stars0 ratingsSecurity with Go: Explore the power of Golang to secure host, web, and cloud services Rating: 0 out of 5 stars0 ratingsVagrant Virtual Development Environment Cookbook Rating: 5 out of 5 stars5/5OpenCart Theme and Module Development Rating: 0 out of 5 stars0 ratingsAngularJS Deployment Essentials Rating: 0 out of 5 stars0 ratingsLearn SQL Database Programming: Query and manipulate databases from popular relational database servers using SQL Rating: 0 out of 5 stars0 ratingsReverse Engineering A Complete Guide - 2021 Edition Rating: 0 out of 5 stars0 ratingsOpenNebula 3 Cloud Computing Rating: 0 out of 5 stars0 ratingsPHP BLUEPRINT: An Essential Beginners Guide to Learn the Realms of PHP From A-Z Rating: 0 out of 5 stars0 ratingsGetting Started with Grunt: The JavaScript Task Runner Rating: 3 out of 5 stars3/5Practical Threat Detection Engineering: A hands-on guide to planning, developing, and validating detection capabilities Rating: 0 out of 5 stars0 ratingsvSphere High Performance Cookbook - Second Edition Rating: 0 out of 5 stars0 ratingsMeteor Cookbook Rating: 5 out of 5 stars5/5Scientific Computing with Scala Rating: 0 out of 5 stars0 ratingsArtificial Intelligence Systems Integration: Fundamentals and Applications Rating: 0 out of 5 stars0 ratingsPHP 5 CMS Framework Development - 2nd Edition Rating: 0 out of 5 stars0 ratingsLearning Python for Forensics Rating: 0 out of 5 stars0 ratingsClean Ruby: A Guide to Crafting Better Code for Rubyists Rating: 0 out of 5 stars0 ratingsPostgreSQL Server Programming - Second Edition Rating: 0 out of 5 stars0 ratingsDocker Networking Cookbook Rating: 0 out of 5 stars0 ratingsPHP Mastery: Crafting Dynamic Web Solutions Rating: 0 out of 5 stars0 ratingsCloud Security & Forensics Handbook: Dive Deep Into Azure, AWS, And GCP Rating: 0 out of 5 stars0 ratingsMastering KnockoutJS Rating: 0 out of 5 stars0 ratings
Information Technology For You
An Ultimate Guide to Kali Linux for Beginners Rating: 3 out of 5 stars3/5CompTIA A+ CertMike: Prepare. Practice. Pass the Test! Get Certified!: Core 1 Exam 220-1101 Rating: 0 out of 5 stars0 ratingsCybersecurity for Beginners : Learn the Fundamentals of Cybersecurity in an Easy, Step-by-Step Guide: 1 Rating: 0 out of 5 stars0 ratingsCreating Online Courses with ChatGPT | A Step-by-Step Guide with Prompt Templates Rating: 4 out of 5 stars4/5Summary of Super-Intelligence From Nick Bostrom Rating: 4 out of 5 stars4/5CompTia Security 701: Fundamentals of Security Rating: 0 out of 5 stars0 ratingsCOMPUTER SCIENCE FOR ROOKIES Rating: 0 out of 5 stars0 ratingsData Analytics for Beginners: Introduction to Data Analytics Rating: 4 out of 5 stars4/5Supercommunicator: Explaining the Complicated So Anyone Can Understand Rating: 3 out of 5 stars3/5Understanding TCP/IP Rating: 4 out of 5 stars4/5How to Find a Wolf in Siberia (or, How to Troubleshoot Almost Anything) Rating: 0 out of 5 stars0 ratingsWordPress Plugin Development: Beginner's Guide Rating: 0 out of 5 stars0 ratingsLinux Command Line and Shell Scripting Bible Rating: 3 out of 5 stars3/5Practical Ethical Hacking from Scratch Rating: 5 out of 5 stars5/5Google Trends Instant Cash Rating: 0 out of 5 stars0 ratingsLearning Microsoft Endpoint Manager: Unified Endpoint Management with Intune and the Enterprise Mobility + Security Suite Rating: 0 out of 5 stars0 ratingsMicrosoft Access for Beginners and Intermediates Rating: 0 out of 5 stars0 ratings20 Windows Tools Every SysAdmin Should Know Rating: 5 out of 5 stars5/5How to Write Effective Emails at Work Rating: 4 out of 5 stars4/5Who Says Elephants Can't Dance?: Leading a Great Enterprise Through Dramatic Change Rating: 4 out of 5 stars4/5The Design Inference Rating: 5 out of 5 stars5/5The iPadOS 17: The Complete User Manual to Quick Set Up and Mastering the iPadOS 17 with New Features, Pictures, Tips, and Tricks Rating: 0 out of 5 stars0 ratingsA Practical Guide Wireshark Forensics Rating: 5 out of 5 stars5/5Inkscape Beginner’s Guide Rating: 5 out of 5 stars5/5CompTIA ITF+ CertMike: Prepare. Practice. Pass the Test! Get Certified!: Exam FC0-U61 Rating: 5 out of 5 stars5/5ChatGPT: The Future of Intelligent Conversation Rating: 4 out of 5 stars4/5Arch Linux: Fast and Light! Rating: 3 out of 5 stars3/5
Reviews for CodeIgniter 1.7
0 ratings0 reviews
Book preview
CodeIgniter 1.7 - David Upton
Table of Contents
CodeIgniter 1.7
Credits
About the Authors
About the Reviewer
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code for the book
Errata
Piracy
Questions
1. Introduction to CodeIgniter
What can CodeIgniter do for you?
Save time
Make your site more robust
Keep your links up-to-date automatically
Preventing database SQL injection attacks and form prepping
Protect your site from XSS attacks
Make your code bolder
Send email attachments without hassles
Save bandwidth by zipping files that users need to download
What CI doesn't do
Yes, but…what is CodeIgniter? What are frameworks?
Comparing CI to other open source solutions (CakePHP and Joomla!)
What to choose
License
Summary
2. Setting up a CodeIgniter Site
Prerequisites
Installing CodeIgniter
Exploring the file structure
Does it work?—checking our CI installation
The configuration file
Autoloading libraries, helpers, and so on
Mod rewrite and apache .htaccess to achieve nice URL rewrites
Moving the application directory and the system directory—benefits
Summary
3. Navigating Your Site
MVC: Model-View-Controller
But how does all this work?
The welcome controller
Working with views
The default controller
CodeIgniter syntax rules
Controller
View
Types of files or classes on a CI site
Designing a better view
Designing a better controller
Getting parameters to a function
Passing data to a view
How CI classes pass information and control to each other
Calling views
Calling functions directly
Interacting with controllers
An example of a CI helper—the URL helper
A simple library example—creating a menu
Summary
4. Using CI to Simplify Databases
Configuration settings
Designing the database for our site
Active Record
Advantages of using the Active Record class
Saving time
Automatic functionality
Read queries
Displaying query results
Create and update queries
Delete queries
Mixing Active Record and classic
styles
Dealing with complex queries
Summary
Chapter appendix: MySQL query to set up the website's database
5. Simplifying HTML Pages and Forms
Writing a view
Long and short PHP syntax and other CodeIgniter style guidelines
File format
PHP closing tag
Nesting views
Practical issues of site architecture
CI's form helper—entering data
Form helper advantage one: Clarity
Form helper advantage two: Automation
My display model
CI's form validation class: Checking data easily
Setting up validation
Setting up the controller
Setting up forms
Let's pack it all together
Summary
6. Simplifying Sessions and Security
Continuing with our practical site using CI
Moving around the site
Security/Sessions: Using another CI library class
Turning sessions into security
But what about logout?
Isn't there anything already built?
Security
Summary
7. CodeIgniter and Objects
Object-oriented programming
The CI super-object
Copying by reference
Adding your own code to the CI super-object
Problems with the CI super-object
Summary
8. Improving Our Application with Third-Party Code
Creating a helper
Creating a library
Sitemap
Explanation for My_Parser.php
Google charts plugin
Summary
9. Using CI to Communicate
Using the FTP class to test remote files
Machines talking to machines again: XML-RPC
Getting the XML-RPC server and client in touch with each other
Formatting XML-RPC exchanges
Debugging
Issues with XML-RPC
Talking to humans for a change—the email class
Summary
10. How CI Helps to Provide Dynamic Information
The date helper—converting and localizing dates
The Calendar class
Working with text—the text helper
Going international—the Language class
Making HTML tables the easy way—the Table class
Caching pages
Summary
11. Using CI to Handle Files and Images
The file helper
The download helper
The file upload class and CI's image class
CI's image class
Easy file compression with CI's zip class
Summary
12. Moving Your Site to the WWW
Errors and error pages
So, should we update if a new version of CI comes out?
Steps/advice to follow when updating our CI version
Summary
13. CRUD—or Putting It All Together
Building our CRUD controller, model, and views
Upgrading our CRUD
Pagination class
Putting some order into our records
Summary
14. The Verdict on CI
Organizing the files of our site
Organizing the logic of our site
A model
A controller
A view
Centralized configuration
Code conventions
Database tools
Simpler and more powerful code
Adding security to our site
Making our site more scalable and our code more reusable
Documentation and community
Summarizing all that CI offers
Summary
15. Resources and Extensions
CI's user forums
Video tutorials
Available plugins and libraries
AJAX or JavaScript
Authentication
PDF generation
Comparisons: Which charting library to use?
HTML purifier
CRUD—the final frontier
Invoicing
Additional resources
Some books that could help
Resources for other programs: XAMPP Lite, MySQL, and PHP
Summary
A. Appendix
What we need to use the library
Adding products to the cart
Showing the cart to our clients
Summary
Index
CodeIgniter 1.7
David Upton
Jose Argudo
CodeIgniter 1.7
Copyright © 2009 Packt Publishing
allows 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 authors, Packt Publishing, nor its dealers or 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 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: November 2009
Production Reference: 1031109
Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN: 978-1-847199-48-5
www.packtpub.com
Cover Image by Vinayak Chittar (<[email protected]>)
Credits
Authors
Jose Argudo Blanco
David Upton
Reviewer
Pascal Kriete
Acquisition Editor
Douglas Paterson
Development Editor
Swapna Verlekar
Technical Editor
Dhwani Devater
Indexer
Hemangini Bari
Editorial Team Leader
Abhijeet Deobhakta
Project Team Leader
Lata Basantani
Project Coordinator
Poorvi Nair
Proofreader
Chris Smith
Graphics
Nilesh R Mohite
Production Coordinator
Dolly Dasilva
Cover Work
Dolly Dasilva
About the Authors
Jose Argudo Blanco is a web developer from Valencia, Spain. After finishing his studies he started working for a web design company. After working for six years for that company and some others, he decided to work as a freelance.
Now, after some years have passed, he thinks it's the best decision he has ever taken—a decision that let him work with the tools he likes, such as CodeIgniter, Joomla!, CakePHP, JQuery, and other well-known open source technologies.
For the past few months he has also reviewed some books for Packt Publishing, such as Magento 1.3 Theme Design, Magento: Beginner's Guide, Joomla! 1.5 SEO, Symfony 1.3 Web Application Development, and Joomla! with Flash. The one yet to be published is Magento Development with PHP.
He has put a lot of effort into this book and hopes it's very useful for the readers.
To my girlfriend Silvia whose support helps me every day, to my brother, maybe some day we will work together, to my parents for being always there, and, of course, to Swapna, Poorvi, and all the Packt team, without their help, and Pascal's advices this book couldn't have been possible.
David Upton is a director of a specialized management consultancy company, based in London but working around the world. His clients include some of the world's largest companies. He is increasingly interested in web-enabling his work, and seeking to turn ideas into robust professional applications by the simplest and easiest route. So far he has written applications for two major companies in the UK. His other interests include simulation, on which he writes a weblog that takes up far too much of his time, and thinking.
About the Reviewer
Pascal Kriete is a developer from Germany. Although his background lies in engineering, after a short, unsuccessful stint in traditional server/client administration he found his way into freelance web development. Looking to streamline his development workflow—as freelancers want to do—he discovered CodeIgniter and began actively participating in the community. This involvement quickly spread to the ExpressionEngine forums and by the end of 2008 Pascal joined the EllisLab team as a Technical Support Specialist. He has since moved on to become a member of the development team, where he continues to polish code and gets to interact with an ever growing number of third-party developers.
Preface
CodeIgniter (CI) is a powerful open source PHP framework with a very small footprint, built for PHP programmers who need a simple and elegant toolkit to create full-featured web applications. CodeIgniter is an MVC framework, similar in some ways to the Rails framework for Ruby, and is designed to enable, not overwhelm. This book explains how to work with CodeIgniter in a clear logical way.
What this book covers
Chapter 1: Introduction to CodeIgniter, will introduce you to what frameworks are, and specifically we will talk about CI and how it can help in our day to day work. We will see what CI offers and what it doesn't.
Chapter 2: Setting up a CodeIgniter Site, will help you to prepare the basic configuration of your site, studying CI's structure and config files. At the end you will have a working CI installation.
Chapter 3: Navigating Your Site, will cover some important topics, like the MVC pattern and how CI handles this pattern, and we will make an example controller just to see how all this works.
Chapter 4: Using CI to Simplify Databases, helps you to start working with databases. This is a very important topic. CI will really help us at this point, so we are going to see in detail all the tools at our disposal, including Active Record.
Chapter 5: Simplifying HTML Pages and Forms, will help you with HTML and form helpers, which are some important tools you will find in CodeIgniter; we will see some examples about their usage and introduce form validation.
Chapter 6: Simplifying Sessions and Security, will cover some important security features of CI, which will help make your site more secure. As we will also talk about sessions we will build a simple login feature.
Chapter 7: CodeIgniter and Objects, introduces a bit on object-oriented programming and how CI makes use of it, including the use of the CI super object, and how we can modify and use it.
Chapter 8: Improving Our Application with Third-Party Code, will help you take some rest from the hard work you have done in the previous chapters. We will see some third-party code that we can easily add to our site, improving it, and adding interesting functionalities.
Chapter 9: Using CI to Communicate, explains how CI helps us in communication. Communication is an important part of every site. We will see the ftp class, email class, and XML-RPC class and, of course, the possibility to add more as we need!
Chapter 10: How CI Helps to Provide Dynamic Information, will show some more useful helpers and classes, this will include the date helper, text helper, and table and language classes. All of this will help in the development of our site, not only in reducing code, but in adding powerful features to our working toolbox.
Chapter 11: Using CI to Handle Files and Images, will be about files, uploading, downloading, and compressing them, of course, all with CI classes! As always those classes will make our life easier. Image treatment also has some space in the chapter as CI has some nice features to crop, reduce, watermark, and so on.
Chapter 12: Moving Your Site to the WWW, will finally show you how to upload your site to a shared host or similar. Here we will see in detail how to do that, and also what kind of error we can expect to encounter.
Chapter 13: CRUD—or Putting It All Together, will be a chapter of putting it all together
, where we'll take time to recap and emphasize the most important topics covered to the moment. Insert, edit, and remove records from the database are some topics we will see here, but also ordering and pagination of results.
Chapter 14: The Verdict on CI, will summarize the key points of CI, not to forget anything, as every little thing CI offers will be of great help.
Chapter 15: Resources and Extensions, will give a list of resources and third-party code—we don't want to reinvent the wheel! We will take a look at some useful extensions such as authentication, PDF generation, invoicing, and much more.
The Appendix will introduce a new and interesting CI feature, the cart class; building a store has never been easier!
What you need for this book
Only basic PHP and HTML knowledge is needed to understand this book. All the rest is explained here from top to bottom. You won't get lost!
Who this book is for
This book is not only for PHP developers who want to be more productive at work, but also for those who are new to web programming and are searching for a useful tool that helps in their work. If you are tired of writing the same code again and again, this book is for you. If you want to create more robust and easier-to-maintain PHP sites, again this book is for you. But this book is really for you if you want to enjoy PHP programming with a framework that really helps you.
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: Our password variable contains a password that looks quite secure, but will produce a problem in our query.
A block of code will be set as follows:
$this->load->database('websites');
$query = $this->db->get('sites');
foreach ($query->result() as $row)
{
print $row->url;
}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items will be shown in bold:
stylesheet type=text/css
href=/
.$css;?>
>
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 our text like this: When you click on the Buy button, you will be returned to this page again
.
Note
Warnings or important notes appear in a box like this.
Note
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 drop an email to <[email protected]>, and mention the book title in the subject of your message.
If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code for the book
Visit http://www.packtpub.com/files/code/9485_Code.zip to directly download the example code.
Note
The downloadable files contain instructions on how to use them.
Errata
Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in text or code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration, and help us to improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata added to any list of existing errata. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
Questions
You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.
Chapter 1. Introduction to CodeIgniter
Most of us just want to write applications that work well, and to do it as simply and easily as we can. This book is about CodeIgniter—a tool for making PHP easy to use.
If you need to produce results, have better and more maintainable code, and you enjoy programming, then you should try using CodeIgniter (CI to its friends). CI is free, lightweight, and simple to install, and it really makes your life much easier. Just read this chapter to find out how:
What CI can do for you?
What is CI? What are Frameworks?
Comparing CI to other open source solutions.
What CI doesn't do?
What can CodeIgniter do for you?
If you are already writing code in PHP, CI will help you to do it in a better and easier way. It will cut down the amount of code you actually type. Your scripts will be easier to read and update—improving team work and maintainability. It will help you to give large websites a coherent structure. It will discipline your code and make it more robust, in some cases even without your knowing it.
That's quite a big claim. You have already spent some time learning PHP, HTML, CSS, a database, and so on. You need basic, not necessarily expert knowledge of PHP to benefit from CI.
CI is not for you if:
You don't have a minimum knowledge of PHP and HTML.
You like to write all of your code. There are people who prefer to write their code instead of using already built solutions. If you are that kind of a person, you should try CI. It is very well commented and, if you are short of time, it will help you. You won't need to reinvent the wheel again and again. CI comes with a lot of helpers, libraries, and much more for the most common tasks. Give it a try!
You don't like PHP; but how is that possible? With a huge community and hordes of code and tools, PHP is one of the favorite languages of the Web.
And definitely CI is not for you if you don't like to finish your projects on time, in a well-structured fashion, and without having to redo the same things again and again.
If you don't belong to any of the categories mentioned in the previous points, keep reading!
Save time
CI doesn't take long to learn, and it quickly pays for your effort in the time saved later. Let's look at a simple measure—how CI cuts down the amount of code you need to type. This is not just good for the lazy. The less you type, the fewer mistakes you make, and the less time you spend debugging your code.
Let's take two examples, (they are explained later in this book, so don't worry now about how they work!). If you are writing a database query, this is how you might write a function within your PHP program to query a MySQL database:
$connection = mysql_connect(localhost
,fred
,12345
);
mysql_select_db(websites
, $connection);
$result = mysql_query (SELECT * FROM sites
, $connection);
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
foreach ($row as $attribute)
print {$attribute[1]}
;
}
Now see how a CI function would handle a similar query:
$this->load->database('websites');
$query = $this->db->get('sites');
foreach ($query->result() as $row)
{
print $row->url;
}
Compare the character count—244 for the traditional syntax and 112 for CI. Another thing that you have to take into account when using Active Record is that you can change your database from MySQL to Postgres (or any other that is supported by CI) and you won't need to change your queries—a very helpful thing.
Now let's take an example where you are writing a