Tag Archives: codeigniter tutorials
Codeigniter File Upload
Codeigniter File Upload: Codeigniter provides uploading classes to upload the files. It provides several options to set restrictions(such as file size, file type) and preferences of the file. Here in this tutorial we are going to explain how you can upload files/Images in Codeigniter.
Codeigniter File Upload | Image Upload Library Example
Let us go step by step to understand how to upload files/images in Codeigniter.
Steps to Upload Files
Following steps are main steps to upload files in codeigniter-
- Upload Form(Html View)
- Controller
- Success Page(Html View)
Upload Form(Html View)
Create a view file as upload_form_view.php in application/views folder. This Html Form contains the form input to select and upload the file –
Codeigniter File Upload | Html Part Example:
|
Controller
Create a controller file as upload.php in application/controllers folder. This will contain the code to upload file on server as below-
Codeigniter File Upload Controller Example:
load->helper(array('form', 'url')); } public function index() { $this->load->view('upload_form_view', array('error' => ' ' )); } public function process_upload() { $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'gif|jpg|png'; $config['max_size'] = 2048; $config['max_width'] = 1000; $config['max_height'] = 800; $this->load->library('upload', $config); if ( ! $this->upload->process_upload('myfile')) { $error = array('error' => $this->upload->display_errors()); $this->load->view('upload_form_view', $error); } else { $data = array('upload_data' => $this->upload->data()); $this->load->view('success_view', $data); } } } ?> |
In controller method process_upload $config array is used to set the preferences and restrictions. Let us have look on the config –
- $config[‘upload_path’] : This is used to set the directory path where images should be uploaded.
- $config[‘max_size’] : This is used to set the maximum file size allowed to be uploaded.
- $config[‘allowed_types’] : This is used to set the file types that will be allowed for upload for example jpg, png etc.
- $config[‘max_width’] : This will set the max with of file allowed.
- $config[‘max_height’] : This will set the max height of file allowed.
Success Page(Html View)
Create a view file as success_view.php in application/views folder. This view will be loaded when the file is uploaded successfully.
Success Page View:
|
Codeigniter Calendar Library
Codeigniter Calendar Library: Codeigniter provides Calendar library which enables us to create calendar dynamically. It provides you flexibility to control the design of the calendar. You can also customize the calendar such as controlling look & feel and passing data into cells etc. Here in this tutorial we are going to explain how you can use this library to create calendars dynamically.
Codeigniter Calender Library
Let us go step by step to understand how codeigniter library can be used –
Load Calendar Library
Before using the calendar library you must load the calendar library. You can load calendar library simply as below –
Codeigniter Load Calendar Library Syntax:
$this->load->library('calendar'); |
Now after loading this library you can use it.
Displaying Calendar
Once the library is loaded you can display the calendar simply as below –
Display | Show Calendar Example:
$this->load->library('calendar'); echo $this->calendar->generate(); |
The above syntax will generate the calendar in the codeigniter. You can also pass data to your calendar cells.
Codeigniter Email Library
Codeigniter Email Library: Codeigniter provides email library to send emails. It is very easy to use this library and send emails. You can configure it on the fly. Here in this tutorial we are going to demonstrate how to use email library in codeigniter and send mails.
Codeigniter Email Library | Send Mail Example
First of all we need to load the mail library before using it. We can load library simply as below-
Syntax
Codeigniter Load Email Library Syntax
$this->load->library('email'); |
Now you can use it to send mails.
Example
Let us create a simple example to send email-
Codeigniter Send Email Example
$this->load->library('email'); $this->email->from('sender@example.com', 'Your Name'); $this->email->to('receiver@example.com'); $this->email->cc('ccmail@example.com'); $this->email->bcc('bcc@example.com'); $this->email->subject('Codeigniter Email Test'); $this->email->message('This is test mail.'); $this->email->send(); |
Learn More
Let us have look over more examples.
Send Attachments
You can also attach some file in email using the following method –
Codeigniter Send Email Example
$this->load->library('email'); $this->email->from('sender@example.com', 'Your Name'); $this->email->to('receiver@example.com'); $this->email->cc('ccmail@example.com'); $this->email->bcc('bcc@example.com'); $this->email->subject('Codeigniter Email Test'); $this->email->message('This is test mail.'); $this->email->attach('http://example.com/myfile.pdf'); // or just give file path $this->email->attach('path/myfile.pdf'); $this->email->send(); |
Send Inline Attachments
If you want to send inline attachments you can use $this->email->attachment_cid() to send inline attachments-
Codeigniter Send Inline(image) Attachments
$this->load->library('email'); $this->email->from('sender@example.com', 'Your Name'); $this->email->to('receiver@example.com'); $this->email->cc('ccmail@example.com'); $this->email->bcc('bcc@example.com'); $this->email->subject('Codeigniter Email Test'); $this->email->message('This is test mail.'); $filename = "images/profile.png"; $cid = $this->email->attachment_cid($filename); $this->email->message(''); $this->email->send(); |
Codeigniter Count Rows Of Table
Codeigniter Count Rows Of Table : There are several ways developers use to get total number of rows in table. You can use $this->db->count_all(‘table_name’) to get the total rows of a table, this is . Here in this tutorial we are going to explain how you can use database class to get the total row count of a table.
Codeigniter Count Rows Of Table | Query Example
The syntax and example to count the rows is as –
Syntax
Codeigniter Count Rows Of Table : Query Syntax
$this->db->count_all('table_name'); |
Where table_name is name of the table.
After running the above query it will give the total count of rows in specified table.
Example
Now suppose we have table “users” and we want to count the number of rows in this table. The example to count rows in “users” table is as –
Codeigniter Count Rows Of Table : Query Example
$totalRows = $this->db->count_all('users'); echo $totalRows; |
The above example will give you total number of rows in users table. Output will be an integer like : 90.
In case of joins use $query->num_rows() to count the results.
Directory Helper
Directory Helper : Codeigniter provides this helper(directory) which is used to work with directories. Here in this tutorial we are going to explain this helper.
Directory Helper
Load Helper
You can load directory helper simply as below –
Codeigniter Directory Helper Example:
$this->load->helper('directory'); |
Functions
Following functions are available in this helper –
directory_map Function
directory_map Function Syntax:
directory_map($source_dir, $directory_depth = 0, $hidden = FALSE); |
Parameters:
- $source_dir (string) – Source directory Path
- $directory_depth (int) – Depth of directories for traversing (0 = fully recursive, 1 = current dir, etc)
- $hidden (bool) – Whether to include hidden directories or not.
- Returns:Array of files
- Return type:array
The above functions gives the array of files in a directory.
Date Helper
Codeigniter Date Helper : Codeigniter provides the helper which is used to work with dates. Here in this tutorial we are going to explain how you can use date helper in Codeigniter. You can use our online editor run and see the output of the example.
Date Helper in Codeigniter
Let us go step by step –
Load Date Helper
First of all load helper(data) before using it. You can the helper(date) simply as below-
Codeigniter Date Helper: Example
$this->load->helper('date'); |
After Loading this helper now you are able to use it’s functions.
Functions of Date Helper
Following functions are present in the date helper.
now Function
This function returns the current time as a UNIX timestamp, referenced by the server’s local time or any other PHP suported timezone based upon the time reference setting in config.
Codeigniter now function syntax
now($timezone = NULL) |
Parameters:
- $timezone (string) – Timezone
- Returns (int) : UNIX timestamp
Now Function Example :
If $timeZone = ‘America/Costa_Rica’; is not passed it will give the time() based on the time_reference settings.
2. mdate Function
This function is somehow similar to the date() function. In addition it enables you to use this function in mysql style date function.
Codeigniter mdate function syntax
mdate($datestr = '', $time = '') |
Parameters:
- $datestr (string) – Date String
- $time (int) – Unix Timestamp
- Returns (int) : String.
mdate Function Example :
Codeigniter mdate function syntax
$datestr = ' %Y - %m - %d - %h:%i %a'; $time = time(); echo mdate($datestr, $time); |
More Functions
Let’s have look over more functions and example.
3. standard_date Function
Codeigniter standard_date function syntax
standard_date($format = 'DATE_RFC822', $time = NULL) |
Parameters:
- $format (string) – Date Format
- $time (int) – Unix Timestamp
- Returns (int) : String.
standard_date Function Example :
Codeigniter standard_date function syntax
$datestr = ' %Y - %m - %d - %h:%i %a'; $time = time(); echo mdate($datestr, $time); |
4. local_to_gmt Function
This function converts the UNIX timestamp into GMT.
Codeigniter local_to_gmt function syntax
local_to_gmt($time = NULL) |
Parameters:
- Returns (int) : Int.
$time (int) – Unix Timestamp
Example :
5. gmt_to_local Function
This function converts GMT timestamp into the localized UNIX timestamp.
Codeigniter gmt_to_local function syntax
gmt_to_local($time = NULL) |
Parameters:
- Returns (int) : Int.
$time (int) – Unix Timestamp
6. mysql_to_unix Function
This function converts mysql timestamp into the UNIX timestamp.
Codeigniter mysql_to_unix function syntax
mysql_to_unix($time = NULL) |
Parameters:
- Returns (int) : Int.
$time (int) – Unix Timestamp
7. unix_to_human Function
This function converts UNIX timestamp to human date format.
Codeigniter unix_to_human function syntax
unix_to_human($time = '', $seconds = FALSE, $format = 'us') |
Parameters:
- $time (int) – Unix Timestamp
- $seconds (bool) – Pass true to show seconds else false.
- $format (string) – String Format.
- Returns (String) : String.
8. human_to_unix Function
This function date into the UNIX timestamp.
Codeigniter human_to_unix function syntax
human_to_unix($dateString) |
Parameters:
- $dateString – Date String
- Returns (Int) : int.
9. nice_date Function
This function takes bad date string and converts it into the proper formatted date..
Codeigniter nice_date function syntax
nice_date($badDate, $format = FALSE) |
Parameters:
- $badDate – Date String not in proper format.
- $format – Format To Be returned.
- Returns (Date) : formatted date.
Example
$badDate = '199005'; $date = nice_date($badDate, 'Y-m-d'); // Will give: 1990-05-01
10. timespan Function
This function formats the UNIX timestamp date..
Codeigniter timespan function syntax
timespan($seconds = 1, $time = '', $units = '') |
Parameters:
- $seconds – No Of seconds.
- $time – UNIX timestamp.
- $units – time unit to return.
- Returns (Date) : formatted date.
11. days_in_month Function
This function returns the number of days in specified year.
Codeigniter days_in_month function syntax
days_in_month($month = 0, $year = '') |
Parameters:
- $month – Month.
- $year – Year.
- Returns (Days) : No of days.
Example
echo days_in_month(08, 2006);
12. date_range Function
This function returns the array of dates between two specified dates.
Codeigniter date_range function syntax
date_range($unix_start = '', $mixed = '', $is_unix = TRUE, $format = 'Y-m-d') |
Parameters:
- $unix_start – UNIX timestamp start date.
- $mixed – UNIX timestamp of the range end date.
- $is_unix – This if set to FALSE if $mixed is not a timestamp.
- $format – Output format.
- Returns (Dates) : Returns all dates within the range.
Example
$dateRange = date_range('2014-03-01', '2014-01-20'); print_r($dateRange); // will give you all dates between the range.
13. timezones Function
This function returns the returns the number of hours offset from UTC using the timestamp.
Codeigniter timezones function syntax
timezones($timezone) |
Parameters:
- $timezone – Numeric timezone.
- Returns (int) : Returns hours diff.
14. timezone_menu Function
This function is used to create the dropdown menu of timezones.
Codeigniter timezone_menu function syntax
timezone_menu($default = 'UTC', $class = '', $name = 'timezones', $attributes = '') |
Parameters:
- $default (string) – Timezone
- $class (string) – Class name
- $name (string) – Menu name
- $attributes (mixed) – HTML attributes
- Returns (HTML) : Returns HTML Dropdown menu of timezones.
Cookie Helper
Codeigniter Cookie Helper contains the functions that are used in working with cookies. Here in this tutorial we are going to explain how you can create cookies using this helper. Let us go step by step to learn about the Cookie Helper.
Cookie Helper in Codeigniter Example
Load This Helper
Before using the helper function you must load this helper as below –
Cookie Helper in Codeigniter Example:
$this->load->helper('cookie'); |
After Loading this function you can use it’s functions.
Cookie Helper Functions
Let us go through the available functions in this helper.
set_cookie Function
Syntax of set_cookie function
Codeigniter set_cookie function syntax:
set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE, $httponly = FALSE); |
Parameters:
- $name (mixed) – Name of Cookie.
- $value (string) – Cookie value.
- $expire (int) – Number of seconds until expiration.
- $domain (string) – Cookie domain ex.- www.tutorialsplane.com.
- $path (string) – Cookie path.
- $prefix (string) – Cookie name prefix.
- $secure (bool) – To send the cookie using HTTPS.
- $httponly (bool) – To hide the cookie from JavaScript.
get_cookie Function
Syntax of get_cookie function
Codeigniter get_cookie function syntax:
get_cookie($index, $xss_clean = NULL); |
Parameters:
- $index (string) – Name of Cookie.
- $xss_clean (bool) – If you want to apply xss filtering to returned value set true else it will be false by default.
Returns:
Returns cookie value. If value not found it will return NULL.
delete_cookie Function
Syntax of delete_cookie function
Codeigniter delete_cookie function syntax:
delete_cookie($index, $domain, $path, $prefix); |
Parameters:
- $name (mixed) – Name of Cookie.
- $domain (string) – Cookie domain ex.- www.tutorialsplane.com.
- $path (string) – Cookie path.
- $prefix (string) – Cookie name prefix.
Returns:
Returns void.
delete_cookie Example
If you do not want to specify other params you can delete the cookies as below –
Codeigniter delete_cookie Example:
delete_cookie('my_cookie'); //my_cookie name of the cookies |
Where my_cookie is name of the cookie.
Examples
Let’s have look over examples on set, get and delete cookie.
Codeigniter Set Cookie Example
You can set cookie value simply as below –
Codeigniter Set Cookie Example :
public function setMyCookie(){ $this->load->helper('cookie'); $cookie = array( 'name' => 'username', 'value' => 'test@tutorialsplane.com', 'expire' => time()+86500, 'domain' => 'www.tutorialsplane.com', // You can add .localhost for local machine 'path' => '/', 'prefix' => 'tutorialsplane_', ); set_cookie($cookie); } |
Codeigniter Get Cookie Example
You can get cookie value simply as below –
Codeigniter Get Cookie Example :
public function getMyCookie(){ $this->load->helper('cookie'); //get_cookie('prefix_name'); $cookieVal = get_cookie('tutorialsplane_username'); echo $cookieVal; } |
Codeigniter Delete Cookie Example
You can delete cookie value simply as below –
Codeigniter delete Cookie Example :
public function deleteMyCookie(){ $this->load->helper('cookie'); // delete cookie example $cookie = array( 'name' => 'username', 'value' => '', 'expire' => '0', 'domain' => 'www.tutorialsplane.com', // You can add .localhost for local machine 'prefix' => 'tutorialsplane_' ); delete_cookie($cookie); } |
The above example will delete the cookie set in the above example.
CAPTCHA Helper
CAPTCHA Helper : Codeigniter provides the CAPTCHA Helper which contains the functions that are used to create CAPTCHA images. Here is in this tutorial we are going to explain how you can create CAPTCHA images using the codeiniter’s CAPTCHA. CAPTCHA is used for human verification. Basically it is used to prevent the automated robots, bots, spams to access the website. CAPTCHA is basically image which contains some random string, numbers which needs to be verified by the user.
CAPTCHA Helper in Codeigniter
Let us go step by step to understand how captcha helper works in codeigniter.
Load CAPTCH Helper
You can load CAPTCHA(helper) simply as below –
Load CAPTCHA Helper in Codeigniter:
$this->load->helper('captcha'); |
Now you can user CAPTCHA(helper) functions to create CAPTCHA images.
How to use Codeigniter CAPTCHA Helper ?
If CAPTCHA(Helper) is loaded you can create CAPTHCA simply as below –
Load CAPTCH(Helper) in Codeigniter:
load->helper('captcha'); $val = array( 'word' => rand(1000, 10000), 'img_path' => './captcha/', 'img_url' => 'http://tutorialsplane.com/runtest/codeigniter/demo/captcha/', 'font_path' => 'arial.ttf', 'img_width' => '200', 'img_height' => 50, 'expiration' => 7200, 'word_length' => 7, 'font_size' => 20, 'img_id' => 'Imageid', 'pool' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'colors' => array( 'background' => array(255, 255, 255), 'border' => array(255, 255, 255), 'text' => array(0, 0, 0), 'grid' => array(255, 40, 40) ) // background : White // border: White //Text: black text and red grid ); $captcha = create_captcha($val); echo $captcha['image']; } } ?> |
In the above example we have created a controller and added a method which handles the captcha generation.
If you run the above example it will produce output something like this –
More About CAPTCHA Helper
Let’s have look over more example and demo here.
Array Helper
Array Helper – Codeigniter Array Helper file contains the functions which are used for arrays. You can load this helper and use it’s functions. Here in this tutorial we are going to explain how you can load array helper in codeigniter and use it’s functions. We will also explain how you can load helper on view file and use it’s functions. You can use our online editor to run and see the output of the example.
Array Helper in Codeigniter
Let us go step by step to understand the codeigniter array helper.
Load Array Helper in Codeigniter
You can load the array helper using the following syntax –
Load Array Helper in Codeigniter Example :
$this->load->helper('array'); |
Let us go through the available
Array Helper Functions
There are following functions available in the codeigniter Helper.
Element
Syntax :
element($item, $array[, $default = NULL]) |
Parameters –
- $item – Item to fetch from array.
- $array – Input array.
- $default – Default value to be returned if array is not valid.
Returns –
Returns NULL on failure. Returns item on success.
This function is used to fetch an item from array. This functions checks the index and its value. If the index value exists it returns the value else it returns NULL or the specified value in third parameter $default.
Example –
Codeigniter Array Helper function – element: Example
901, 'sku' => 'red-bounce', 'color' => 'gray', 'price' => '' ); echo element('id', $array); // will return 901 echo element('price', $array); // return null echo element('price', $array, '$99'); // return $99 ?>` |
Elements
Syntax :
elements($items, $array[, $default = NULL]) |
Parameters –
- $items – Array of Items to fetch from array.
- $array – Input array.
- $default – Default value to be returned if array is not valid.
Returns –
Returns NULL on failure. Returns items on success.
This function is used to fetch multiple items from an array. This functions checks the index and value of each array item is set or not. If the index value exists it returns the value else it returns NULL or the specified value in third parameter $default.
Example –
Codeigniter Array Helper function – element: Example
901, 'sku' => 'red-bounce', 'color' => 'gray', 'price' => '' ); echo elements(array('id','sku'), $array); // will return array('id'=>901, 'sku'=>'red-bounce'); echo elements(array('id','sku', 'price'), $array); // will return array('id'=>901, 'sku'=>'red-bounce', 'price'=>NUll); echo elements('price', $array, '$99'); // return array('id'=>901, 'sku'=>'red-bounce', 'price'=>$99); ?>` |
Random Element
This returns the random element from the specified array.
Syntax :
random_element($array) |
Where $array is input array.
Example
Syntax :
$array = array(1, 100, 21, 34, 589, 90, 192); echo random_element($array); // will give any random number |