Comments 0

Document transcript

CodeIgniter User Guide

Welcome to CodeIgniter

CodeIgniter is an Application Development Framework-

a toolkit-

for people who buildweb sites using PHP. Its goal is to enable you to develop projects much faster than youcould if you were writing code from scratch, by providing a rich set of libraries forcommonly needed tasks, as well as a simple interface and logical structure to access theselibraries. CodeIgniter lets you creatively focus on your project by minimizing the amountof code needed for agiven task.

Who is CodeIgniter For?

CodeIgniter is right for you if:



You want a framework with a small footprint.



You need exceptional performance.



You need broad compatibility with standard hosting accounts that run a variety ofPHP versions and configurations.



You want a framework that requires nearly zero configuration.



You want a framework that does not require you to use the command line.



You want a framework that does not require you to adhere to restrictive codingrules.



You are not interested in large-scale monolithic libraries like PEAR.



You do not want to be forced to learn a templating language (although a templateparser is optionally available if you desire one).

This license is a legal agreement between you and EllisLab Inc. for the use ofCodeIgniter Software (the "Software"). By obtaining the Software you agree to complywith the terms and conditions of this license.

Permitted Use

You are permitted to use, copy, modify, and distribute the Software and itsdocumentation, with or without modification, for any purpose, provided that thefollowing conditions are met:

1.

A copy of this license agreement must be included with the distribution.

2.

Redistributions of source code must retain the above copyright notice in all sourcecode files.

3.

Redistributions in binary form must reproduce the above copyright notice in thedocumentation and/or other materials provided with the distribution.

4.

Any files that have been modified must carry notices stating the nature of thechange and the names of those who changed them.

5.

Products derived from the Software must include an acknowledgment that

theyare derived from CodeIgniter in their documentation and/or other materialsprovided with the distribution.

6.

Products derived from the Software may not be called "CodeIgniter", nor may"CodeIgniter" appear in their name, without prior written permission fromEllisLab, Inc.

Indemnity

You agree to indemnify and hold harmless the authors of the Software and anycontributors for any direct, indirect, incidental, or consequential third-party claims,actions or suits, as well as any related expenses, liabilities, damages, settlements or feesarising from your use or misuse of the Software, or a violation of any terms of thislicense.

Disclaimer of Warranty

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,EXPRESSED OR IMPLIED, INCLUDING, BUT NOTLIMITED TO, WARRANTIESOF QUALITY, PERFORMANCE, NON-INFRINGEMENT, MERCHANTABILITY,OR FITNESS FOR A PARTICULAR PURPOSE.

Limitations of Liability

YOU ASSUME ALL RISK ASSOCIATED WITH THE INSTALLATION AND USEOF THE SOFTWARE. IN NO EVENT SHALL THE AUTHORS ORCOPYRIGHTHOLDERS OF THE SOFTWARE BE LIABLE FOR CLAIMS, DAMAGES OROTHER LIABILITY ARISING FROM, OUT OF, OR IN CONNECTION WITH THESOFTWARE. LICENSE HOLDERS ARE SOLELY RESPONSIBLE FORDETERMINING THE APPROPRIATENESS OF USE AND ASSUME ALL RISKSASSOCIATED WITH ITS USE, INCLUDING BUT NOT LIMITED TO THE RISKSOF PROGRAM ERRORS, DAMAGE TO EQUIPMENT, LOSS OF DATA ORSOFTWARE PROGRAMS, OR UNAVAILABILITY OR INTERRUPTION OFOPERATIONS.

Credits

CodeIgniter was originally developed byRick Ellis

(CEO ofEllislab, Inc.). Theframework was written for performance in the real world, with many of the classlibraries, helpers, and sub-systems borrowed from the code-base ofExpressionEngine.

It is currently developed and maintained by the ExpressionEngine Development Team.

A hat tip goes to Ruby on Rails for inspiring us to create a PHP framework, and forbringing frameworks into the general consciousness of the web community.

Installation

Installation Instructions

CodeIgniter is installed in four steps:

1.

Unzip the package.

2.

Upload the CodeIgniter folders and files to your server. Normally the index.phpfile will be at your root.

3.

Open theapplication/config/config.php

file with a text editor and set your baseURL. If you intend to use encryption or sessions, set your encryption key.

4.

If you intend to use a database, open theapplication/config/database.php

file witha text editor and set your database settings.

If you wish to increase security by hiding the location of your CodeIgniter files you canrename thesystem

folder to something more private. If you do rename it, you must openyour mainindex.php

If you find that no matter what you put in your URL only your default page is loading, itmight be that your server does not support the PATH_INFO variable needed to servesearch-engine friendly URLs. As a first step, open yourapplication/config/config.php

fileand look for theURI Protocol

information. It will recommend that you try a couplealternate settings. If it still doesn't work after you've tried this you'll need to forceCodeIgniter to add a question mark to your URLs. To do this open yourapplication/config/config.php

file and change this:

$config['index_page'] = "index.php";

To this:

$config['index_page'] = "index.php?";

Introduction

Getting Started With CodeIgniter

Any software application requires some effort to learn. We've done our best to minimizethe learning curve while making the process as enjoyable as possible.

The first step is toinstall

CodeIgniter, then read all the topics in theIntroduction

sectionof the Table of Contents.

Next, read each of theGeneral Topics

pages in order. Each topic builds on the previousone, and includes code examples that you are encouraged to try.

Once you understand the basics you'll be ready to explore theClass Reference

andHelper Reference

pages to learn to utilize the native libraries and helper files.

Feel free to take advantage of ourCommunity Forums

if you have questions or problems,and ourWiki

to see code examples posted by other users.

CodeIgniter at a Glance

CodeIgniter is an Application Framework

CodeIgniter is a toolkit for people who build web application using PHP. Its goal is

toenable you to develop projects much faster than you could if you were writing code fromscratch, by providing a rich set of libraries for commonly needed tasks, as well as asimple interface and logical structure to access these libraries. CodeIgniterlets youcreatively focus on your project by minimizing the amount of code needed for a giventask.

CodeIgniter is Free

CodeIgniter is licensed under an Apache/BSD-style open source license so you can use ithowever you please. For more information pleaseread thelicense agreement.

CodeIgniter Runs on PHP 4

CodeIgniter is written to be compatible with PHP 4. Although we would have loved totake advantage of the better object handling in PHP 5 since it would have simplifiedsome things we had to find creative solutions for (looking your way, multipleinheritance), at the time of this writing PHP 5 is not in widespread use, which means wewould be alienating most of our potential audience. Major OS vendors like RedHat aremoving slowly to support PHP 5, and they are unlikely to do so in the short term, so wefelt that it did not serve the best interests of the PHP community to write CodeIgniter inPHP 5.

Note: CodeIgniter will run on PHP 5. It simply does not take advantage of any nativefeatures that are only available in that version.

CodeIgniter is Light Weight

Truly light weight. The core system requires only a few very small libraries. This is instark contrast to many frameworks that require significantly more resources. Additionallibraries are loaded dynamically upon request, based on your needs for a given process,so the base system is very lean and quite fast.

CodeIgniter is Fast

Really fast. We challenge you to find a framework that hasbetter performance thanCodeIgniter.

CodeIgniter Uses M-V-C

CodeIgniter uses the Model-View-Controller approach, which allows great separationbetween logic and presentation. This is particularly good for projects in which designersare working with your template files, as the code these file contain will be minimized.We describe MVC in more detail on its own page.

CodeIgniter Generates Clean URLs

The URLs generated by CodeIgniter are clean and search-engine friendly. Rather thanusing the standard "querystring" approach to URLs that is synonymous with dynamicsystems, CodeIgniter uses a segment-based approach:

example.com/news/article/345

Note: By default the index.php file is included in the URL but it can be removed using asimple .htaccess file.

CodeIgniter Packs a Punch

CodeIgniter comes with full-range of libraries that enable the most commonly neededweb development tasks, like accessing a database, sending email, validating form data,maintaining sessions, manipulating images, working with XML-RPCdata and muchmore.

CodeIgniter is Extensible

The system can be easily extended through the use of plugins and helper libraries, orthrough class extensions or system hooks.

CodeIgniter Does Not Require a Template Engine

Although CodeIgniterdoes

come with

a simple template parser that can be optionallyused, it does not force you to use one. Template engines simply can not match theperformance of native PHP, and the syntax that must be learned to use a template engineis usually only marginally easier than learning the basics of PHP. Consider this block ofPHP code:

<ul>

<?php foreach ($addressbook as $name):?>

<li><?=$name?></li>

<?php endforeach; ?>

</ul>

Contrast this with the pseudo-code used by a template engine:

<ul>

{foreach from=$addressbookitem="name"}

<li>{$name}</li>

{/foreach}

</ul>

Yes, the template engine example is a bit cleaner, but it comes at the price ofperformance, as the pseudo-code must be converted back into PHP to run. Since one ofour goals ismaximum performance, we opted to not require the use of a template engine.

CodeIgniter is Thoroughly Documented

Programmers love to code and hate to write documentation. We're no different, of course,but since documentation isas important

as the code itself, we are committed to doing it.Our source code is extremely clean and well commented as well.

CodeIgniter has a Friendly Community of Users

Our growing community of users can be seen actively participating in ourCommunityForums.

CodeIgniter Cheatsheets

Library Reference

Helpers Reference

CodeIgniter Features

Features in and of themselves are a very poor way to judge an application since they tellyou nothing about the user experience, or how intuitively or intelligently it is designed.Features don't reveal anything about the quality of the code, or theperformance, or theattention to detail, or security practices. The only way to really judge an app is to try itand get to know the code.Installing

CodeIgniter is child's play so we encourage you to dojust that. In the mean time here's a list of CodeIgniter's main features.

The index.php serves as the front controller, initializing the base resources neededto run CodeIgniter.

2.

The Router examines the HTTP request to determine what should be done with it.

3.

If a cache file exists, it is sent directly to the browser, bypassing the normalsystem execution.

4.

Security. Before the application controller is loaded, the HTTP request and anyuser submitted data

is filtered for security.

5.

The Controller loads the model, core libraries, plugins, helpers, and any otherresources needed to process the specific request.

6.

The finalized View is rendered then sent to the web browser to be seen. If cachingis enabled, theview is cached first so that on subsequent requests it can be served.

CodeIgniter URLs

By default, URLs in CodeIgniter are designed to be search-engine and human friendly.Rather than using the standard "query string" approach to URLs that is synonymous withdynamic systems, CodeIgniter uses asegment-based

approach:

example.com/news/article/my_article

Note:

Query string URLs can be optionally enabled, as described below.

URI Segments

The segments in the URL, in following with the Model-View-Controller approach,usually represent:

example.com/class/function/ID

1.

The first segment represents the controllerclass

that should be invoked.

2.

The second segment represents the classfunction, or method, that should becalled.

3.

The third, and any additional segments,represent the ID and any variables thatwill be passed to the controller.

TheURI Class

and theURL Helper

contain functions that make it easy to work with yourURI data. In addition, your URLs can be remapped using theURI Routing

feature formore flexibility.

Removing the index.php file

By default, theindex.php

file will be included in your URLs:

example.com/index.php/news/article/my_article

You can easily remove this file by using a .htaccess file with some simple rules. Here isan example of such a file, using the "negative" method in which everything is redirectedexcept the specified items:

RewriteEngine on

RewriteCond $1 !^(index\.php|images|robots\.txt)

RewriteRule ^(.*)$ /index.php/$1 [L]

In the above example, any HTTP request other than those for index.php, images, androbots.txt is treated as a request for your index.php file.

Adding a URL Suffix

In yourconfig/config.php

file you can specify a suffix that will be added to all URLsgenerated by CodeIgniter. For example, if a URL is this:

example.com/index.php/products/view/shoes

You can optionally add a suffix, like.html, making the page appear to be of a certaintype:

example.com/index.php/products/view/shoes.html

Enabling Query Strings

In some cases you might prefer to use query strings URLs:

index.php?c=products&m=view&id=345

CodeIgniter optionally supports this capability, which can be enabled in yourapplication/config.php

file. If you open your config file you'll see these items:

$config['enable_query_strings'] = FALSE;

$config['controller_trigger'] = 'c';

$config['function_trigger'] = 'm';

If you change "enable_query_strings" to TRUE this feature will become active. Yourcontrollers and functions will then be accessible using the "trigger" words you've set toinvoke your controllers and methods:

index.php?c=controller&m=method

Please note:

If you are using query strings you will have to build your own URLs, ratherthan utilizing the URL helpers (and other helpers that generate URLs, like some of theform helpers) as these are designed to work with segment based URLs.