资源说明:This is to help with Codeigniter workshop as conducted by me.
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:  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
', '
'); ?>
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.  *Sublime Text 2 Download Page*  *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:
- =$name?>
-
{foreach from=$addressbook item="name"}
- {$name} {/foreach}
'; } //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:  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:
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: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. |
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:
Your file was successfully uploaded!
-
$value):?>
- :
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. |
``` 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.Item | Description |
---|---|
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. |
'; } **$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
本源码包内暂不包含可直接显示的源代码文件,请下载源码包。