ci_manual
文件大小: unknow
源码售价: 5 个金币 积分规则     积分充值
资源说明:This is to help with Codeigniter workshop as conducted by me.
Codeigniter Workshop Manual
===========================

The workshop will be held for three days with 5 session in total. Each session will start with simple explanation and hands on example. Then it is followed by excercises for the parcipant to try and experience the details of each example.

Few assumptions before starting:

- Participants are familiar with programming with PHP
- Participants are using Windows OS
- Internet connection are available

Sessions Topic are as follows:

- Session 0: **Environment Preparation**  
- Session 1: **Intro to CodeIgniter (Installation and PreTest)**  
- Session 2: **MVC Pattern With CodeIgniter**  
- Session 3: **CodeIgniter Common Tools and Helpers**  
- Session 4: **Custom Library and Helpers**  
- Session 5: **CodeIgniter Best Practice**
- Project: **Simple ACL and News Board ala Reddit**

The What
--------

CodeIgniter is an Application Development Framework - a toolkit - for people who build web sites using PHP. Its goal is to enable you to **develop projects much faster** than you could if you were writing code from scratch, by providing a rich set of libraries for commonly needed tasks, as well as a **simple interface** and **logical structure** to access these libraries. CodeIgniter lets you creatively focus on your project by minimizing the amount of code needed for a given task.

The Why
-------

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 of PHP 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 coding rules**.
- You do not want to be forced to learn a templating language (although a template parser is optionally available if you desire one).
- You eschew complexity, favoring **simple solutions**.
- You need clear, **thorough documentation**.


Session 0 : Environment Preparation
===================================

Before we can start, we need to make sure our tools are well prepared. This workshop use only 2 tools which is Sublime Text 2 as text editor and WAMPP as our local server.

Sublime Text 2
--------------
Example are written using text editor Sublime Text 2. Download it [here](http://sublimetext.com) and install it.

![Download Sublime Text 2](https://raw.github.com/robotys/ci_manual/master/assets/sublime_download.png)

*Sublime Text 2 Download Page*

![Sublime Text 2 UI Example](https://raw.github.com/robotys/ci_manual/master/assets/sublime_example.png)

*Sublime Text Example*


WAMPP
-----

Apache, MySQL, PHP and PHPMyAdmin were installed using WAMPP packaged. Download it here and install it. Please make sure to install Microsoft C++ redistributable package before installing WAMPP.


Session 1:  Intro to CodeIgniter (Installation and PreTest)
===========================================================

CODEIGNITER AT A GLANCE
-----------------------
	
Some overview about CodeIgniter


CodeIgniter is an Application Framework
---------------------------------------
CodeIgniter is a toolkit for people who build web applications using PHP. Its goal is to enable you to develop projects much faster than you could if you were writing code from scratch, by providing a rich set of libraries for commonly needed tasks, as well as a simple interface and logical structure to access these libraries. CodeIgniter lets you creatively focus on your project by minimizing the amount of code needed for a given task.

CodeIgniter is Free
-------------------
CodeIgniter is licensed under an Apache/BSD-style open source license so you can use it however you please. For more information please read the license agreement.

CodeIgniter is Light Weight
---------------------------
Truly light weight. The core system requires only a few very small libraries. This is in stark contrast to many frameworks that require significantly more resources. Additional libraries 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 has better performance than CodeIgniter.

CodeIgniter Uses M-V-C
----------------------
CodeIgniter uses the Model-View-Controller approach, which allows great separation between logic and presentation. This is particularly good for projects in which designers are 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 than using the standard "query string" approach to URLs that is synonymous with dynamic systems, 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 a simple .htaccess file.

CodeIgniter Packs a Punch
-------------------------
CodeIgniter comes with full-range of libraries that enable the most commonly needed web development tasks, like accessing a database, sending email, validating form data, maintaining sessions, manipulating images, working with XML-RPC data and much more.

CodeIgniter is Extensible
--------------------------
The system can be easily extended through the use of your own libraries, helpers, or through class extensions or system hooks.

CodeIgniter Does Not Require a Template Engine
----------------------------------------------
Although CodeIgniter does come with a simple template parser that can be optionally used, it does not force you to use one. Template engines simply can not match the performance of native PHP, and the syntax that must be learned to use a template engine is usually only marginally easier than learning the basics of PHP. Consider this block of PHP code:

	
Contrast this with the pseudo-code used by a template engine:
    {foreach from=$addressbook item="name"}
  • {$name}
  • {/foreach}
Yes, the template engine example is a bit cleaner, but it comes at the price of performance, as the pseudo-code must be converted back into PHP to run. Since one of our goals is maximum 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 is as important as the code itself, we are committed to doing it. Our source code is extremely clean and well commented as well. INSTALLATION ------------ Download Codeigniter [here](http://codeigniter.com/download.php) Extract (unzip) to home folder (www or htdocs) so it looks like this: -www -codeigniter -application -system -user_guide -index.php If you like, change the name codeigniter into CI, so its simple to be called afterwards. -www -ci -application -system -user_guide -index.php However, we can change the folder structure to whatever we like. Structure as depicted below are quite widely used for codeigniter: -www -app_name -application -index.php -another_app -application -index.php -ci_system Just make sure we specify the location of systems file for the application to approriate location. Open the index.php file and change the system path to the new one: $system_path = '../ci_system'; This folder structure can cater multiple application within one domain with only one codeigniter core files (system). This make the upgrading easier and faster. To use multiple Codeigniter core for multiple application, so that we can fallback gracefully should something happen, we can use folder structure as below: -www -app_name -application -index.php -another_app -application -index.php -ci_system_v21 -ci_system_v22 ... and specify which application to use which version of codeigniter in its own index.php. Test the installation by loading the app via url: http://localhost/app_name Latest 'test page' design should be like below: ![Codeigniter Welcome page](https://raw.github.com/robotys/ci_manual/master/assets/ci_welcome.png) And thus your installation is now complete! For some *nightmare* you can open application folder and wonder what is all the folder and files are doing. (Or you can always open the user_guide folder tor the helpful documents.) > **Exercise 0: Your App** Create your codeigniter App with system folder outside of your app_folder. Make sure the test page run fine. /debug Session 2: MVC Pattern With CodeIgniter ======================================= Codeigniter assume the codes are structured into MVC pattern. MVC separate the concerns of codes into 3 distinct function namely: 1. **Models** Models are where the heavy processing is done. All the business process, database operation (CRUD) is done here. We always prefer Fat Models over Fat Controller 2. **Controller** Controller is the one who route the url to specified php class and method. Controller acts like traffic light which control the flow of data to be processed and flow of page to be display as view. 3. **View** View only manage the front-end aspect of our web app. All the designs/htmls and CSS are manage by view part of MVC. CodeIgniter has a fairly loose approach to MVC since **Models are not required**. If you don't need the added separation, or find that maintaining models requires more complexity than you want, you **can ignore them** and build your application minimally using Controllers and Views. > CodeIgniter also enables you to incorporate your own existing scripts, or even develop core libraries for the system, enabling you to work in a way that makes the most sense to you. The simplest flow of information for CodeIgniter app are as followed: 1. A page is requested via url. Lets say Dashboard page. The url used is http://localhost/app_name/index.php/dashboard 2. Codeigniter System will translate the uri and run the method **index** in class **Dashboard** from php file named **dashboard.php** inside *app_name/application/controller* folder. -www -app_name -application -controllers -dashboard.php -index.php -ci_system dashboard.php contains codes as below: ```php class Dashboard extend CI_Controller{ function index(){ echo 'Welcome To Dashboard'; } } ``` here we can see that Codeigniter will run and display 'Welcome To Dashboard'. No Models and Views involved in this example. More complex example when the data, lets say the string 'Welcome To Dashboard' is processed from models and the send to view files. For this example we will create two new files at *application/models/m_dashboard.php* and another one at *application/view/v_dashboard.php*: -www -app_name -application -controllers -dashboard.php -models -m_dashboard.php -views -v_dashboard.php -index.php -ci_system Change the **dashboard.php** into this: ```php class Dashboard extend CI_Controller{ function index(){ $this->load->model('m_dashboard'); $str = $this->m_dashboard->index_data(); $data['index'] = $str; $this->load->view('v_dashboard, $data); } } ``` As we can see, the dashboard controller will first load the models that it need by using load method. This load method is inherited from CI_Controller parent. All models loaded can then be called via *$this->model_name->model_method()* to initiate the models method process. Here we will run method *index_data()* which will return the string 'Welcome To Dashboard'. Fill the **m_dashboard.php** file with codes as below: class M_dashboard extend CI_Model{ function index_data(){ return 'Welcome To Dashboard'; } } It is really direct. The code will return string 'Welcome To Dashboard' to whoever calling it. As per example, the one who call it is variable $str in dashboard controller. The string then loaded into array $data with key 'index' and sent to view via load method second parameter as shown in the example. $this->load->view('view_files', $second_parameter); THe view files then will capture the string into new variable based on the key. So here, the key contain the string within array data is 'index', thus in view files codeigniter will spawn new variable with the name $index containing the string. Fill in the **v_dashboard.php** files with the codes below: ```php Dashboard '.$index.''; ?> ``` We can see that v_dashboard.php resembles a lot like plain html files. Keep in mind that view files are like front end template to our application and we will populate it from data sent from controller. Example here is the string 'Welcome To Dashboard' which was sent in variable $index. > **Exercise 1: Add new page** > Add new page which is linked from dashboard to url *http://localhost/app_name/index.php/dashboard/info* . The view page should display php_info() details. > **Exercise 2: Views List** > Add new page which is linked from dashboard to url *http://localhost/app_name/index.php/admin/view_list* . The view page should display all file names within view directory dynamically. Session 2.1: MVC with string from MySQL DB ------------------------------------------ A lot of data we need usually reside in mysql database. Codeigniter is not limited to only MySQL. In fact CI can connect to multitude of DB engine via its powerful DB connectors wizard. But MySQL is good enough for example. Before we start we need to have the connection to MySQL DB. Open database.php within config directory located at *www/app_name/application/config/database.php*. Change the details to reflect your MySQL connection. As this is local MySQL under WAMP, we can just use the default username and password. the three important details to be changed are: ```php 52: $db['default']['username'] = 'root'; 53: $db['default']['password'] = ''; 54: $db['default']['database'] = 'ci_workshop'; ``` After that, we need to create and populate a MySQL database 'ci_workshop' with appropriate table and data. CI has great tools for Database Management within Database Class. The tools is Database Forge. Create new method in *m_dashboard.php* called db_init and type the codes below: ```php class M_dashboard extend CI_Model{ function index_data(){ return 'Welcome To Dashboard'; } function db_init() { //load database tools $this->load->dbforge(); //create database 'ci_workshop' if ($this->dbforge->create_database('ci_workshop')) { echo 'Database created!
'; } //declare fields for our table $fields = array( 'id' => array( 'type' => 'INT', 'constraint' => 5, 'unsigned' => TRUE, 'auto_increment' => TRUE ), 'key' => array( 'type' => 'VARCHAR', 'constraint' => '100', ), 'value' => array( 'type' => 'text', ) ); //add fields to dbforge tools $this->dbforge->add_field($fields); //set column id as Primary key $this->dbforge->add_key('id', TRUE); //create table if not exists $this->dbforge->create_table('kv_store', TRUE); //load database $this->load->database(); //insert string value to table $this->db->insert('kv_store', array('key'=>'dashboard_welcome','value'=>'Welcome To Dashboard')); } } ``` Change the **dashboard.php** into this: ```php class Dashboard extend CI_Controller{ function index(){ $this->load->model('m_dashboard'); $str = $this->m_dashboard->index_data(); $data['index'] = $str; $this->load->view('v_dashboard', $data); } function init_db(){ $this->load->model('m_dashboard'); $this->m_dashboard->db_init(); echo 'DB now ready!'; } } ``` Run the database initiation by visiting page init_db at *http://localhost/ci_workshop/index.php/dashboard/init_db* If we check in our PhpMyAdmin, we can see that new row has been added in our kv_store table as shown: ![Welcome string in DB](https://raw.github.com/robotys/ci_manual/master/assets/db_welcome.png) Now, to use the strng in our models. Open our m_dashboard.php files and change the code to be like the code shown below: class M_dashboard extend CI_Model{ function index_data(){ $this->load->database(); $this->db->where('key','dashboard_welcome'); $query = $this->db->get('kv_store'); $res = $query->result_array(); return $res[0]['value']; } } When we run the dashboard page again we will get the same "Welcome To Dashboard" string but it is now reside inside a database. We thus can make a basic CRUD interface to manage the string afterwards. Session 3: CodeIgniter Common Tools and Helpers =============================================== CodeIgniter come with multitude of tools to help our application development. Anything that is conceived for us to be used should already be there in CodeIgniter bag of tools. The tools come from two different place namely Library and Helpers. Codeigniter Library ------------------- CodeIgniter Library is a collection of PHP **Class** which focus on single domain of usage. Among widely use Codeigniter Library are: - **Session Class** Manage $_SESSION but we can choose to make the session either as protected cookies or a table in DB. - **Form Validation Class** Manage input validation before processing. Use with Input Class. Validation include email validation, min,max, numeric, alphanumeric and custom function (usually to check username availability). - **Input Class** Manage native $_POST, $_GET and $_SERVER global variable. Automatically sanitize the value before process. - **Email Class** Ultimate tools to send email via PHP script. All type of configuration and email types (plain text, html email, attachment) available. - **File Uploading Class** Manage file uploads function gracefully. Simple and elegant solution. - **URI Class** To help with URL segmentation and manipulation. From URI string to array and vice versa. Best used to manage complex ACL. - **Database Class** The most beloved class especially in Model. Among smaller tools within database class is Active Record which can add structure and logic to our SQL query. - **Caching Class** Simple yet effective caching solution. Can be extend to use external caching tools to make it more efficient and powerfull. Codeigniter Helper ------------------ Codeigniter Helper is a collection of **functions** that can be use to help us in developing our application. Helpers differ from Library in sense of helper is a function while Library is a method within a class. Helpers is more focused as a tool and thus only cater limited usage space. Among usefull helpers are: - **Download Helper** Assist us in creating a download page. All type of files can be used. received filename and binary data as parameters. - **Email Helper** Two functions within this helper are ```valid_email('string@email')``` to validate email string and ```send_email('recipient','subject','message')``` to send plain text email. Simple and functional. - **Form Helper** Assist us in creating html form and input tags. May not be shorter than html but its usefullness come from its powerfull logic and configurations. - **URL Helper** Assist us in generating uri within Codeigniter application. Thus we not need to change every links as it is now dynamically generated by codeigniter. Some of the library need to be loaded first before it can be used while other are automatically loaded. Helpers are always needed to be loaded. Below are the functionlity of said Class and Helpers: Session Class ------------- The Session class permits you maintain a user's "state" and track their activity while they browse your site. The Session class stores session information for each user as serialized (and optionally encrypted) data in a cookie. It can also store the session data in a database table for added security, as this permits the session ID in the user's cookie to be matched against the stored session ID. By default only the cookie is saved. If you choose to use the database option you'll need to create the session table as indicated below. **INITIALIZE** Sessions will typically run globally with each page load, so the session class must either be initialized in your controller constructors, or it can be auto-loaded by the system. For the most part the session class will run unattended in the background, so simply initializing the class will cause it to read, create, and update sessions. To initialize the Session class manually in your controller constructor, use the ```$this->load->library``` function: $this->load->library('session'); Once loaded, the Sessions library object will be available using: ```$this->session``` **How do Sessions work?** When a page is loaded, the session class will check to see if valid session data exists in the user's session cookie. If sessions data does not exist (or if it has expired) a new session will be created and saved in the cookie. If a session does exist, its information will be updated and the cookie will be updated. With each update, the session_id will be regenerated. It's important for you to understand that once initialized, the Session class runs automatically. There is nothing you need to do to cause the above behavior to happen. You can, as you'll see below, work with session data or even add your own data to a user's session, but the process of reading, writing, and updating a session is automatic. **USAGE** //Load the library $this->load->library('session'); //set new session value like array. $this->session->set_userdata($array); ///usage: $newdata = array( 'username' => 'johndoe', 'email' => 'johndoe@some-site.com', 'logged_in' => TRUE ); $this->session->set_userdata($newdata); //or like this also can: $this->session->set_userdata('some_name', 'some_value'); //retrieve session with key 'item' $this->session->userdata('item'); //example of usage: $session_id = $this->session->userdata('session_id'); //Retrieve All Session Data $this->session->all_userdata() //Unset Session Data $this->session->unset_userdata('some_name'); //Session Destroy $this->session->sess_destroy(); Thats a simple all in one how to use Codeigniter Session Library > **Brain Nuggets:** Think a login and login system using Codeigniter Session Form Validation --------------- **OVERVIEW** Before explaining CodeIgniter's approach to data validation, let's describe the ideal scenario: 1. A form is displayed. 2. You fill it in and submit it. 3. If you submitted something invalid, or perhaps missed a required item, the form is redisplayed containing your data along with an error message describing the problem. 4. This process continues until you have submitted a valid form. On the receiving end, the script must: 1. Check for required data. 2. Verify that the data is of the correct type, and meets the correct criteria. For example, if a username is submitted it must be validated to contain only permitted characters. It must be of a minimum length, and not exceed a maximum length. The username can't be someone else's existing username, or perhaps even a reserved word. Etc. 3. Sanitize the data for security. 4. Pre-format the data if needed (Does the data need to be trimmed? HTML encoded? Etc.) 5. Prep the data for insertion in the database. Although there is nothing terribly complex about the above process, it usually requires a significant amount of code, and to display error messages, various control structures are usually placed within the form HTML. Form validation, while simple to create, is generally very messy and tedious to implement. **Form Validation Tutorial** What follows is a "hands on" tutorial for implementing CodeIgniters Form Validation. In order to implement form validation you'll need three things: A View file containing a form. A View file containing a "success" message to be displayed upon successful submission. A controller function to receive and process the submitted data. Let's create those three things, using a member sign-up form as the example. **The Form** Using a text editor, create a form called myform.php. In it, place this code and save it to your applications/views/ folder: My Form ', '
'); ?>
Username
Password
Password Confirm
Email Address
**The Success Page** Using a text editor, create a form called formsuccess.php. In it, place this code and save it to your applications/views/ folder: My Form

Your form was successfully submitted!

**The Controller** Using a text editor, create a controller called form.php. In it, place this code and save it to your applications/controllers/ folder: class Form extends CI_Controller { function index() { //load form and url helper $this->load->helper(array('form', 'url')); //load form validation class $this->load->library('form_validation'); //set validation rules for all $this->form_validation->set_rules('username', 'Username', 'trim|callback_username_check|required|min_length[5]|max_length[12]|xss_clean'); $this->form_validation->set_rules('password', 'Password', 'trim|required|matches[passconf]|md5'); $this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required'); $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email'); //run validation, if false display myform, if true display formsuccess if ($this->form_validation->run() == FALSE) { $this->load->view('myform'); } else { $this->load->view('formsuccess'); } } //Special function to check if the username is allowed to be used. public function username_check($str) { if ($str == 'test') { //set error message for username_check rules. $this->form_validation->set_message('username_check', 'The %s field can not be the word "test"'); return FALSE; } else { return TRUE; } } } To test the application, open ```http://localhost/ci_workshop/index.php/form```, complete the form and hit enter. Play with the application to try the validation. **EXPLANATION** There is three main section of Form Validation Class which is 1: Error Display, 2: Validation Rules and 3: Run Validation. The one with the most complexity among the three are Validation Rules. The validation process basically are like below: 1. Validation start with capturing the input from html form via input class. 2. The value then will be run through all the required rules which has been setup in validation rules section. 3. Any error while validating will be notified via Error Display function (validation_errors). **RULE REFERENCE** The following is a list of all the native rules that are available to use:
Rule Parameter Description Example
required No Returns FALSE if the form element is empty.  
matches Yes Returns FALSE if the form element does not match the one in the parameter. matches[form_item]
is_unique Yes Returns FALSE if the form element is not unique to the table and field name in the parameter. is_unique[table.field]
min_length Yes Returns FALSE if the form element is shorter then the parameter value. min_length[6]
max_length Yes Returns FALSE if the form element is longer then the parameter value. max_length[12]
exact_length Yes Returns FALSE if the form element is not exactly the parameter value. exact_length[8]
greater_than Yes Returns FALSE if the form element is less than the parameter value or not numeric. greater_than[8]
less_than Yes Returns FALSE if the form element is greater than the parameter value or not numeric. less_than[8]
alpha No Returns FALSE if the form element contains anything other than alphabetical characters.  
alpha_numeric No Returns FALSE if the form element contains anything other than alpha-numeric characters.  
alpha_dash No Returns FALSE if the form element contains anything other than alpha-numeric characters, underscores or dashes.  
numeric No Returns FALSE if the form element contains anything other than numeric characters.  
integer No Returns FALSE if the form element contains anything other than an integer.  
decimal Yes Returns FALSE if the form element is not exactly the parameter value.  
is_natural No Returns FALSE if the form element contains anything other than a natural number: 0, 1, 2, 3, etc.  
is_natural_no_zero No Returns FALSE if the form element contains anything other than a natural number, but not zero: 1, 2, 3, etc.  
valid_email No Returns FALSE if the form element does not contain a valid email address.  
valid_emails No Returns FALSE if any value provided in a comma separated list is not a valid email.  
valid_ip No Returns FALSE if the supplied IP is not valid.  
valid_base64 No Returns FALSE if the supplied string contains anything other than valid Base64 characters.  
> Note: These rules can also be called as discrete functions. For example: ```$this->form_validation->required($string)``` > Note: You can also use any native PHP functions that permit one parameter. Input Clas ---------- The Input Class serves two purposes: - It pre-processes global input data for security. - It provides some helper functions for fetching input data and pre-processing it. >Note: This class is initialized automatically by the system so there is no need to do it manually. **Security Filtering** The security filtering function is called automatically when a new controller is invoked. It does the following: - If $config['allow_get_array'] is FALSE(default is TRUE), destroys the global GET array. - Destroys all global variables in the event register_globals is turned on. - Filters the GET/POST/COOKIE array keys, permitting only alpha-numeric (and a few other) characters. - Provides XSS (Cross-site Scripting Hacks) filtering. This can be enabled globally, or upon request. - Standardizes newline characters to \n(In Windows \r\n) - XSS Filtering The Input class has the ability to filter input automatically to prevent cross-site scripting attacks. If you want the filter to run automatically every time it encounters POST or COOKIE data you can enable it by opening your application/config/config.php file and setting this: $config['global_xss_filtering'] = TRUE; Please refer to the Security class documentation for information on using XSS Filtering in your application. **Using POST, COOKIE, or SERVER Data** CodeIgniter comes with three helper functions that let you fetch POST, COOKIE or SERVER items. The main advantage of using the provided functions rather than fetching an item directly ($_POST['something']) is that the functions will check to see if the item is set and return false (boolean) if not. This lets you conveniently use data without having to test whether an item exists first. In other words, normally you might do something like this: if ( ! isset($_POST['something'])) { $something = FALSE; } else { $something = $_POST['something']; } With CodeIgniter's built in functions you can simply do this: $something = $this->input->post('something'); The three functions are: - ```$this->input->post()``` - ```$this->input->cookie()``` - ```$this->input->server()``` **$this->input->post()** The first parameter will contain the name of the POST item you are looking for: $this->input->post('some_data'); The function returns FALSE (boolean) if the item you are attempting to retrieve does not exist. The second optional parameter lets you run the data through the XSS filter. It's enabled by setting the second parameter to boolean TRUE; $this->input->post('some_data', TRUE); To return an array of all POST items call without any parameters. To return all POST items and pass them through the XSS filter set the first parameter NULL while setting the second parameter to boolean; The function returns FALSE (boolean) if there are no items in the POST. $this->input->post(NULL, TRUE); // returns all POST items with XSS filter $this->input->post(); // returns all POST items without XSS filter **$this->input->get()** This function is identical to the post function, only it fetches get data: $this->input->get('some_data', TRUE); To return an array of all GET items call without any parameters. To return all GET items and pass them through the XSS filter set the first parameter NULL while setting the second parameter to boolean; The function returns FALSE (boolean) if there are no items in the GET. $this->input->get(NULL, TRUE); // returns all GET items with XSS filter $this->input->get(); // returns all GET items without XSS filtering **$this->input->get_post()** This function will search through both the post and get streams for data, looking first in post, and then in get: $this->input->get_post('some_data', TRUE); **$this->input->cookie()** This function is identical to the post function, only it fetches cookie data: $this->input->cookie('some_data', TRUE); **$this->input->server()** This function is identical to the above functions, only it fetches server data: $this->input->server('some_data'); **$this->input->set_cookie()** Sets a cookie containing the values you specify. There are two ways to pass information to this function so that a cookie can be set: Array Method, and Discrete Parameters: *Array Method* Using this method, an associative array is passed to the first parameter: $cookie = array( 'name' => 'The Cookie Name', 'value' => 'The Value', 'expire' => '86500', 'domain' => '.some-domain.com', 'path' => '/', 'prefix' => 'myprefix_', 'secure' => TRUE ); $this->input->set_cookie($cookie); > Notes: > Only the name and value are required. To delete a cookie set it with the expiration blank. > The expiration is set in seconds, which will be added to the current time. Do not include the time, but rather only the number of seconds from now that you wish the cookie to be valid. If the expiration is set to zero the cookie will only last as long as the browser is open. > For site-wide cookies regardless of how your site is requested, add your URL to the domain starting with a period, like this: .your-domain.com > The path is usually not needed since the function sets a root path. > The prefix is only needed if you need to avoid name collisions with other identically named cookies for your server. > The secure boolean is only needed if you want to make it a secure cookie by setting it to TRUE. *Discrete Parameters* If you prefer, you can set the cookie by passing data using individual parameters: $this->input->set_cookie($name, $value, $expire, $domain, $path, $prefix, $secure); **$this->input->cookie()** Lets you fetch a cookie. The first parameter will contain the name of the cookie you are looking for (including any prefixes): cookie('some_cookie'); The function returns FALSE (boolean) if the item you are attempting to retrieve does not exist. The second optional parameter lets you run the data through the XSS filter. It's enabled by setting the second parameter to boolean TRUE; cookie('some_cookie', TRUE); **$this->input->ip_address()** Returns the IP address for the current user. If the IP address is not valid, the function will return an IP of: 0.0.0.0 echo $this->input->ip_address(); $this->input->valid_ip($ip) Takes an IP address as input and returns TRUE or FALSE (boolean) if it is valid or not. Note: The $this->input->ip_address() function above validates the IP automatically. if ( ! $this->input->valid_ip($ip)) { echo 'Not Valid'; } else { echo 'Valid'; } Email Class ----------- CodeIgniter's robust Email Class supports the following features: - Multiple Protocols: Mail, Sendmail, and SMTP - Multiple recipients - CC and BCCs - HTML or Plaintext email - Attachments - Word wrapping - Priorities - BCC Batch Mode, enabling large email lists to be broken into small BCC batches. - Email Debugging tools **Sending Email** Sending email is not only simple, but you can configure it on the fly or set your preferences in a config file. Here is a basic example demonstrating how you might send email. Note: This example assumes you are sending the email from one of your controllers. $this->load->library('email'); $this->email->from('your@example.com', 'Your Name'); $this->email->to('someone@example.com'); $this->email->cc('another@another-example.com'); $this->email->bcc('them@their-example.com'); $this->email->subject('Email Test'); $this->email->message('Testing the email class.'); $this->email->send(); echo $this->email->print_debugger(); Email Function Reference ------------------------ **$this->email->from()** Sets the email address and name of the person sending the email: $this->email->from('you@example.com', 'Your Name'); **$this->email->reply_to()** Sets the reply-to address. If the information is not provided the information in the "from" function is used. Example: $this->email->reply_to('you@example.com', 'Your Name'); **$this->email->to()** Sets the email address(s) of the recipient(s). Can be a single email, a comma-delimited list or an array: $this->email->to('someone@example.com'); $this->email->to('one@example.com, two@example.com, three@example.com'); $list = array('one@example.com', 'two@example.com', 'three@example.com'); $this->email->to($list); **$this->email->cc()** Sets the CC email address(s). Just like the "to", can be a single email, a comma-delimited list or an array. **$this->email->bcc()** Sets the BCC email address(s). Just like the "to", can be a single email, a comma-delimited list or an array. **$this->email->subject()** Sets the email subject: $this->email->subject('This is my subject'); **$this->email->message()** Sets the email message body: $this->email->message('This is my message'); **$this->email->set_alt_message()** Sets the alternative email message body: $this->email->set_alt_message('This is the alternative message'); This is an optional message string which can be used if you send HTML formatted email. It lets you specify an alternative message with no HTML formatting which is added to the header string for people who do not accept HTML email. If you do not set your own message CodeIgniter will extract the message from your HTML email and strip the tags. **$this->email->clear()** Initializes all the email variables to an empty state. This function is intended for use if you run the email sending function in a loop, permitting the data to be reset between cycles. foreach ($list as $name => $address) { $this->email->clear(); $this->email->to($address); $this->email->from('your@example.com'); $this->email->subject('Here is your info '.$name); $this->email->message('Hi '.$name.' Here is the info you requested.'); $this->email->send(); } If you set the parameter to TRUE any attachments will be cleared as well: $this->email->clear(TRUE); **$this->email->send()** The Email sending function. Returns boolean TRUE or FALSE based on success or failure, enabling it to be used conditionally: if ( ! $this->email->send()) { // Generate error } **$this->email->attach()** Enables you to send an attachment. Put the file path/name in the first parameter. Note: Use a file path, not a URL. For multiple attachments use the function multiple times. For example: $this->email->attach('/path/to/photo1.jpg'); $this->email->attach('/path/to/photo2.jpg'); $this->email->attach('/path/to/photo3.jpg'); $this->email->send(); **$this->email->print_debugger()** Returns a string containing any server messages, the email headers, and the email messsage. Useful for debugging. File Uploading Class -------------------- CodeIgniter's File Uploading Class permits files to be uploaded. You can set various preferences, restricting the type and size of the files. **The Process** Uploading a file involves the following general process: An upload form is displayed, allowing a user to select a file and upload it. When the form is submitted, the file is uploaded to the destination you specify. Along the way, the file is validated to make sure it is allowed to be uploaded based on the preferences you set. Once uploaded, the user will be shown a success message. To demonstrate this process here is brief tutorial. Afterward you'll find reference information. **Creating the Upload Form** Using a text editor, create a form called upload_form.php. In it, place this code and save it to your applications/views/ folder: Upload Form

You'll notice we are using a form helper to create the opening form tag. File uploads require a multipart form, so the helper creates the proper syntax for you. You'll also notice we have an $error variable. This is so we can show error messages in the event the user does something wrong. **The Success Page** Using a text editor, create a form called upload_success.php. In it, place this code and save it to your applications/views/ folder: Upload Form

Your file was successfully uploaded!

**The Controller** Using a text editor, create a controller called upload.php. In it, place this code and save it to your applications/controllers/ folder: load->helper(array('form', 'url')); } function index() { $this->load->view('upload_form', array('error' => ' ' )); } function do_upload() { $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'gif|jpg|png'; $config['max_size'] = '100'; $config['max_width'] = '1024'; $config['max_height'] = '768'; $this->load->library('upload', $config); if ( ! $this->upload->do_upload()) { $error = array('error' => $this->upload->display_errors()); $this->load->view('upload_form', $error); } else { $data = array('upload_data' => $this->upload->data()); $this->load->view('upload_success', $data); } } } ?> **The Upload Folder** You'll need a destination folder for your uploaded images. Create a folder at the root of your CodeIgniter installation called uploads and set its file permissions to 777. **Try it!z** To try your form, visit your site using a URL similar to this one: example.com/index.php/upload/ You should see an upload form. Try uploading an image file (either a jpg, gif, or png). If the path in your controller is correct it should work. **Initializing the Upload Class** Like most other classes in CodeIgniter, the Upload class is initialized in your controller using the $this->load->library function: $this->load->library('upload'); Once the Upload class is loaded, the object will be available using: $this->upload **Setting Preferences** Similar to other libraries, you'll control what is allowed to be upload based on your preferences. In the controller you built above you set the following preferences: $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'gif|jpg|png'; $config['max_size'] = '100'; $config['max_width'] = '1024'; $config['max_height'] = '768'; $this->load->library('upload', $config); // Alternately you can set preferences by calling the initialize function. Useful if you auto-load the class: $this->upload->initialize($config); The above preferences should be fairly self-explanatory. Below is a table describing all available preferences. **Preferences** The following preferences are available. The default value indicates what will be used if you do not specify that preference.
Preference Default Value Options Description
upload_path None None The path to the folder where the upload should be placed. The folder must be writable and the path can be absolute or relative.
allowed_types None None The mime types corresponding to the types of files you allow to be uploaded. Usually the file extension can be used as the mime type. Separate multiple types with a pipe.
file_name None Desired file name

If set CodeIgniter will rename the uploaded file to this name. The extension provided in the file name must also be an allowed file type.

overwrite FALSE TRUE/FALSE (boolean) If set to true, if a file with the same name as the one you are uploading exists, it will be overwritten. If set to false, a number will be appended to the filename if another with the same name exists.
max_size 0 None The maximum size (in kilobytes) that the file can be. Set to zero for no limit. Note: Most PHP installations have their own limit, as specified in the php.ini file. Usually 2 MB (or 2048 KB) by default.
max_width 0 None The maximum width (in pixels) that the file can be. Set to zero for no limit.
max_height 0 None The maximum height (in pixels) that the file can be. Set to zero for no limit.
max_filename 0 None The maximum length that a file name can be. Set to zero for no limit.
encrypt_name FALSE TRUE/FALSE (boolean) If set to TRUE the file name will be converted to a random encrypted string. This can be useful if you would like the file saved with a name that can not be discerned by the person uploading it.
remove_spaces TRUE TRUE/FALSE (boolean) If set to TRUE, any spaces in the file name will be converted to underscores. This is recommended.
**Setting preferences in a config file** If you prefer not to set preferences using the above method, you can instead put them into a config file. Simply create a new file called the upload.php, add the $config array in that file. Then save the file in: config/upload.php and it will be used automatically. You will NOT need to use the $this->upload->initialize function if you save your preferences in a config file. **Function Reference** The following functions are available **$this->upload->do_upload()** Performs the upload based on the preferences you've set. Note: By default the upload routine expects the file to come from a form field called userfile, and the form must be a "multipart type:
If you would like to set your own field name simply pass its value to the do_upload function: $field_name = "some_field_name"; $this->upload->do_upload($field_name) **$this->upload->display_errors()** Retrieves any error messages if the do_upload() function returned false. The function does not echo automatically, it returns the data so you can assign it however you need. *Formatting Errors* By default the above function wraps any errors within ```

``` tags. You can set your own delimiters like this: $this->upload->display_errors('

', '

'); **$this->upload->data()** This is a helper function that returns an array containing all of the data related to the file you uploaded. Here is the array prototype: Array ( [file_name] => mypic.jpg [file_type] => image/jpeg [file_path] => /path/to/your/upload/ [full_path] => /path/to/your/upload/jpg.jpg [raw_name] => mypic [orig_name] => mypic.jpg [client_name] => mypic.jpg [file_ext] => .jpg [file_size] => 22.2 [is_image] => 1 [image_width] => 800 [image_height] => 600 [image_type] => jpeg [image_size_str] => width="800" height="200" ) **Explanation** Here is an explanation of the above array items.
ItemDescription
file_name The name of the file that was uploaded including the file extension.
file_type The file's Mime type
file_path The absolute server path to the file
full_path The absolute server path including the file name
raw_name The file name without the extension
orig_name The original file name. This is only useful if you use the encrypted name option.
client_name The file name as supplied by the client user agent, prior to any file name preparation or incrementing.
file_ext The file extension with period
file_size The file size in kilobytes
is_image Whether the file is an image or not. 1 = image. 0 = not.
image_width Image width.
image_height Image height
image_type Image type. Typically the file extension without the period.
image_size_str A string containing the width and height. Useful to put into an image tag.
URI Class --------- The URI Class provides functions that help you retrieve information from your URI strings. If you use URI routing, you can also retrieve information about the re-routed segments. > Note: This class is initialized automatically by the system so there is no need to do it manually. $this->uri->segment(n) Permits you to retrieve a specific segment. Where n is the segment number you wish to retrieve. Segments are numbered from left to right. For example, if your full URL is this: http://example.com/index.php/news/local/metro/crime_is_up The segment numbers would be this: 1. news 2. local 3. metro 4. crime_is_up By default the function returns FALSE (boolean) if the segment does not exist. There is an optional second parameter that permits you to set your own default value if the segment is missing. For example, this would tell the function to return the number zero in the event of failure: $product_id = $this->uri->segment(3, 0); It helps avoid having to write code like this: if ($this->uri->segment(3) === FALSE) { $product_id = 0; } else { $product_id = $this->uri->segment(3); } **$this->uri->rsegment(n)** This function is identical to the previous one, except that it lets you retrieve a specific segment from your re-routed URI in the event you are using CodeIgniter's URI Routing feature. **$this->uri->slash_segment(n)** This function is almost identical to $this->uri->segment(), except it adds a trailing and/or leading slash based on the second parameter. If the parameter is not used, a trailing slash added. Examples: $this->uri->slash_segment(3); $this->uri->slash_segment(3, 'leading'); $this->uri->slash_segment(3, 'both'); Returns: 1. segment/ 2. /segment 3. /segment/ **$this->uri->slash_rsegment(n)** This function is identical to the previous one, except that it lets you add slashes a specific segment from your re-routed URI in the event you are using CodeIgniter's URI Routing feature. **$this->uri->uri_to_assoc(n)** This function lets you turn URI segments into and associative array of key/value pairs. Consider this URI: index.php/user/search/name/joe/location/UK/gender/male Using this function you can turn the URI into an associative array with this prototype: [array] ( 'name' => 'joe' 'location' => 'UK' 'gender' => 'male' ) The first parameter of the function lets you set an offset. By default it is set to 3 since your URI will normally contain a controller/function in the first and second segments. Example: $array = $this->uri->uri_to_assoc(3); echo $array['name']; The second parameter lets you set default key names, so that the array returned by the function will always contain expected indexes, even if missing from the URI. Example: $default = array('name', 'gender', 'location', 'type', 'sort'); $array = $this->uri->uri_to_assoc(3, $default); If the URI does not contain a value in your default, an array index will be set to that name, with a value of FALSE. Lastly, if a corresponding value is not found for a given key (if there is an odd number of URI segments) the value will be set to FALSE (boolean). **$this->uri->ruri_to_assoc(n)** This function is identical to the previous one, except that it creates an associative array using the re-routed URI in the event you are using CodeIgniter's URI Routing feature. **$this->uri->assoc_to_uri()** Takes an associative array as input and generates a URI string from it. The array keys will be included in the string. Example: $array = array('product' => 'shoes', 'size' => 'large', 'color' => 'red'); $str = $this->uri->assoc_to_uri($array); // Produces: product/shoes/size/large/color/red **$this->uri->uri_string()** Returns a string with the complete URI. For example, if this is your full URL: http://example.com/index.php/news/local/345 The function would return this: /news/local/345 **$this->uri->ruri_string()** This function is identical to the previous one, except that it returns the re-routed URI in the event you are using CodeIgniter's URI Routing feature. **$this->uri->total_segments()** Returns the total number of segments. **$this->uri->total_rsegments()** This function is identical to the previous one, except that it returns the total number of segments in your re-routed URI in the event you are using CodeIgniter's URI Routing feature. **$this->uri->segment_array()** Returns an array containing the URI segments. For example: $segs = $this->uri->segment_array(); foreach ($segs as $segment) { echo $segment; echo '
'; } **$this->uri->rsegment_array()** This function is identical to the previous one, except that it returns the array of segments in your re-routed URI in the event you are using CodeIgniter's URI Routing feature. Database (Active Record) Class ------------------------------ CodeIgniter uses a modified version of the Active Record Database Pattern. This pattern allows information to be retrieved, inserted, and updated in your database with minimal scripting. In some cases only one or two lines of code are necessary to perform a database action. CodeIgniter does not require that each database table be its own class file. It instead provides a more simplified interface. Beyond simplicity, a major benefit to using the Active Record features is that it allows you to create database independent applications, since the query syntax is generated by each database adapter. It also allows for safer queries, since the values are escaped automatically by the system. Note: If you intend to write your own queries you can disable this class in your database config file, allowing the core database library and adapter to utilize fewer resources. ***Selecting Data*** The following functions allow you to build SQL SELECT statements. > Note: If you are using PHP 5 you can use method chaining for more compact syntax. This is described at the end of the page. **$this->db->get();** Runs the selection query and returns the result. Can be used by itself to retrieve all records from a table: $query = $this->db->get('mytable'); // Produces: SELECT * FROM mytable The second and third parameters enable you to set a limit and offset clause: $query = $this->db->get('mytable', 10, 20); // Produces: SELECT * FROM mytable LIMIT 20, 10 (in MySQL. Other databases have slightly different syntax) You'll notice that the above function is assigned to a variable named $query, which can be used to show the results: $query = $this->db->get('mytable'); foreach ($query->result() as $row) { echo $row->title; } **$this->db->get_where();** Identical to the above function except that it permits you to add a "where" clause in the second parameter, instead of using the ```db->where()``` function: $query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset); > Note: get_where() was formerly known as getwhere(), which has been removed **$this->db->select();** Permits you to write the SELECT portion of your query: $this->db->select('title, content, date'); $query = $this->db->get('mytable'); // Produces: SELECT title, content, date FROM mytable > Note: If you are selecting all (*) from a table you do not need to use this function. When omitted, CodeIgniter assumes you wish to SELECT * ```$this->db->select()``` accepts an optional second parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks. This is useful if you need a compound select statement. $this->db->select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4') AS amount_paid', FALSE); $query = $this->db->get('mytable'); **$this->db->select_max();** Writes a "SELECT MAX(field)" portion for your query. You can optionally include a second parameter to rename the resulting field. $this->db->select_max('age'); $query = $this->db->get('members'); // Produces: SELECT MAX(age) as age FROM members $this->db->select_max('age', 'member_age'); $query = $this->db->get('members'); // Produces: SELECT MAX(age) as member_age FROM members **$this->db->select_min();** Writes a "SELECT MIN(field)" portion for your query. As with select_max(), You can optionally include a second parameter to rename
本源码包内暂不包含可直接显示的源代码文件,请下载源码包。