Category Archives: Codeigniter Tutorial

Codeigniter Image Manipulation Class Library


Codeigniter Image Manipulation Class Library – We can load image manuipulation class library like this $this->load->library(‘image_lib’);. This library provide various functions that are used for image resizing, thumbnail creation, image cropping, image rotating and image watermarking. It has three major image libraries supported – GD/GD2, NetPBM and ImageMagick. Here in this tutorial, we are going to explain how to use image manipulation class library.


Codeigniter image manipulation class library

Let us understand how image manipulation class library works in codeigniter with examples.

Load image manipulation class library

First load image manipulation class library to use its functions, this library can be loaded simply as below-

How to load image manipulation class library:

$this->load->library('image_lib');

Functions:-

There are following functions available in image manipulation class library. Now let us understand one by one with example.

  • 1. Processing an image.
  • 3. Image watermarking.

1. Processing an image

This method performs resizing, cropping, rotation, or watermarking of image :-

EXAMPLE

Here is simple example of Processing an image function.

Controller code:-

Your controller code now look like this:-

load->library('image_lib', $config);
		echo $this->image_lib->resize();
		echo $this->image_lib->display_errors();
	}
}?>

2. Image watermarking

Two types of watermarking :-

There are two types of watermarking that we can use.

  • 1. Text.
  • 2. Overlay.

EXAMPLE

Controller code:-

Your controller code now look like this:-

load->library('image_lib');
$config['image_library'] = 'gd2';
$config['source_image']  = 'uploads/Jellyfish.jpg';
$config['new_image']  = './imagesManupulation/abcd.jpg';
$config['wm_text'] = "Tutorialsplane.com";
$config['wm_type'] = 'text';
$config['wm_font_path'] = './media/arial.ttf';
$config['wm_font_size'] = '16';
$config['wm_font_color'] = '#229954';
$config['wm_font_size'] = '40';
$config['wm_vrt_alignment'] = 'middle';
$config['wm_hor_alignment'] = 'center';
$config['wm_padding'] = '20';
$this->image_lib->initialize($config);
$watermark = $this->image_lib->watermark();
echo "Watermark=".$watermark."
"; echo $this->image_lib->display_errors(); } } ?>

Output will be like this.

Class reference:-

There are following references available in image manipulation class library. Now we will explain one by one.

1. Initialize.

This function is used to initialize the class for processing an image.

initialize([$props = array()])
  • Parameters.
  • $props (array) : Image processing preferences
  • Returns : TRUE on success, FALSE in case of invalid settings
  • Returns type : Bool

2. Resize.

This is used to resizing the image and create a copy without resizing.

resize()
  • Parameters.
  • Returns : TRUE on success, FALSE on failure
  • Returns type : Bool

3. Crop.

This is used to crop image and set preferences in x and y axis(in pixels).

crop()
  • Parameters.
  • Returns : TRUE on success, FALSE on failure
  • Returns type : Bool

EXAMPLE

Here is simple example of crop class.

Controller code:-

Your controller code now look like this:-

public function crop()
{
$this->load->library('image_lib');
$config['image_library'] = 'gd2';
$config['source_image'] = 'uploads/Hydrangeas.jpg';
$config['new_image']  = 'imagesManupulation/hydra.jpg';
$config['quality'] = "100%";
$config['maintain_ratio'] = FALSE;
$config['width'] = 231;
$config['height'] = 154;
$config['x_axis'] = '0';
$config['y_axis'] = '0';
$this->image_lib->initialize($config);
echo $this->image_lib->crop();
if ( ! $this->image_lib->crop())
{
	echo $this->image_lib->display_errors();
}}

4. Rotate.

This method is used to rotate the image.

rotate()
  • Parameters.
  • Returns : TRUE on success, FALSE on failure
  • Returns type : Bool

EXAMPLE

Here is simple example of rotate class.

Controller code:-

Your controller code now look like this:-

public function rotate()
{
$this->load->library('image_lib');
$config['image_library'] = 'gd2';
$config['source_image'] = 'uploads/Desert.jpg';
$config['rotation_angle'] = 'hor';
$this->image_lib->initialize($config);
if ( ! $this->image_lib->rotate())
{
   echo $this->image_lib->display_errors();
}
}

5. Watermark.

Watermark class is used to set text/overlap watermark over an image.

watermark()
  • Parameters.
  • Returns : TRUE on success, FALSE on failure
  • Returns type : Bool

6. Clear.

Clear method is used to reset all the value used when processing an image.

clear()
  • Parameters.
  • Returns type : Void

7. Display errors.

This method is used to return all the detected error in string form.

display_errors([$open = '

[$close = '

']])
  • Parameters.
  • $open (string) : Error message opening tag
  • $close (string) : Error message closing tag
  • Returns : Error messages
  • Returns type : String

EXAMPLE

Here is simple example of display error class.

Controller code:-

Your controller code now look like this:-

load->library('image_lib');
$config['image_library'] = 'netpbm';
$config['library_path'] = 'localhost/CodeIgniter/application/libraries';
$config['source_image'] = 'uploads/Desert.jpg';
$config['rotation_angle'] = 'hor';
$this->image_lib->initialize($config);
if ( ! $this->image_lib->rotate())
{
	echo $this->image_lib->display_errors();
}}}
?>

Codeigniter FTP Class Library


Codeigniter FTP Class Library – We can load codeigniter ftp class library like this $this->load->library(‘ftp’);. This library provide permits you to be transfered file to remote server. Remote file can be move , rename and delete. This library permit entire local directory to be recreated remotely with FTP class. Here in this tutorial, we are going to explain how to use FTP class library.


Codeigniter FTP class library

Let us understand how FTP class library works in codeigniter with examples.

Load FTP class library

First load FTP class library to use its functions, this library can be loaded simply as below-

How to load FTP class library:

$this->load->library('ftp');

Class reference:-

There are following references available in ftp class library. Now we will explain one by one.

1. Connect.

This function is used to Connects and logs to the FTP server.

connect([$config = array()])
  • Parameters.
  • $config (array) : Connection values
  • Returns : TRUE on success, FALSE on failure
  • Returns type : Bool

EXAMPLE

Here is simple example of connect class.

Controller code:-

Your controller code now look like this:-

load->library('ftp');
$config['hostname'] = 'localhost';
$config['username'] = 'root';
$config['password'] = '';
$config['debug']    = TRUE;
$this->ftp->connect($config);
}}
?>

2. Uploads.

This is used to uploads a file to your server.

upload($locpath, $rempath[$mode = 'auto'[$permissions = NULL]])
  • Parameters.
  • $locpath (string) : Local file path
  • $rempath (string) : Remote file path
  • $mode (string) : FTP mode, defaults to ‘auto’ (options are: ‘auto’, ‘binary’, ‘ascii’)
  • $permissions (int) : File permissions (octal)
  • Returns : TRUE on success, FALSE on failure
  • Returns type : Bool

EXAMPLE

Here is simple example of upload class.

Controller code:-

Your controller code now look like this:-

load->library('ftp');
$config['hostname'] = 'localhost';
$config['username'] = 'root';
$config['password'] = '';
$config['debug']    = TRUE;
$this->ftp->connect($config);
$this->ftp->upload('local path to folder', 'myfile.html', 'ascii', 0775);
$this->ftp->close();
}}
?>

3. Download.

This is used to download a file from your server.

download($rempath, $locpath[$mode = 'auto'])
  • Parameters.
  • $locpath (string) : Local file path
  • $rempath (string) : Remote file path
  • $mode (string) : FTP mode, defaults to ‘auto’ (options are: ‘auto’, ‘binary’, ‘ascii’)
  • Returns : TRUE on success, FALSE on failure
  • Returns type : Bool

EXAMPLE

Here is simple example of download class.

Controller code:-

Your controller code now look like this:-

load->library('ftp');
$config['hostname'] = 'localhost';
$config['username'] = 'root';
$config['password'] = '';
$config['debug']    = TRUE;
$this->ftp->connect($config);
$this->ftp->download('myfile.html', 'local path to folder', 'ascii');
$this->ftp->close();
}}
?>

4. Rename.

This method permits you to rename your file.

rename($old_file, $new_file[$move = FALSE])
  • Parameters.
  • $old_file (string) : Old file name
  • $new_file (string) : New file name
  • $move (bool) : Whether a move is being performed
  • Returns : TRUE on success, FALSE on failure
  • Returns type : Bool

EXAMPLE

Here is simple example of rename class.

Controller code:-

Your controller code now look like this:-

load->library('ftp');
$config['hostname'] = 'localhost';
$config['username'] = 'root';
$config['password'] = '';
$config['debug']    = TRUE;
$this->ftp->connect($config);
$this->ftp->rename('myfile.html', 'file.html');
$this->ftp->close();
}}
?>

5. Move.

Move class is used to move a file.

move($old_file, $new_file)
  • Parameters.
  • $old_file (string) : Old file name
  • $new_file (string) : New file name
  • Returns : TRUE on success, FALSE on failure
  • Returns type : Bool

EXAMPLE

Here is simple example of move class.

Controller code:-

Your controller code now look like this:-

load->library('ftp');
$config['hostname'] = 'localhost';
$config['username'] = 'root';
$config['password'] = '';
$config['debug']    = TRUE;
$this->ftp->connect($config);
$this->ftp->move('old path', 'new path');
$this->ftp->close();
}}
?>

6. Delete file.

Delete method is used to delete a file.

delete_file($filepath)
  • Parameters.
  • $filepath (string) : Path to file to delete
  • Returns : TRUE on success, FALSE on failure
  • Returns type : Bool

EXAMPLE

Here is simple example of delete file class.

Controller code:-

Your controller code now look like this:-

load->library('ftp');
$config['hostname'] = 'localhost';
$config['username'] = 'root';
$config['password'] = '';
$config['debug']    = TRUE;
$this->ftp->connect($config);
$this->ftp->delete_file('filepath');
$this->ftp->close();
}}
?>

7. Delete directory.

This method is used to delete a directory.

delete_dir($filepath)
  • Parameters.
  • $filepath (string) : Path to directory to delete
  • Returns : TRUE on success, FALSE on failure
  • Returns type : Bool

EXAMPLE

Here is simple example of delete directory class.

Controller code:-

Your controller code now look like this:-

load->library('ftp');
$config['hostname'] = 'localhost';
$config['username'] = 'root';
$config['password'] = '';
$config['debug']    = TRUE;
$this->ftp->connect($config);
$this->ftp->delete_dir('path directory');
$this->ftp->close();
}}
?>

8. List files.

This function gives permit to retrieve a list of file on your server return as an array.

list_files([$path = '.'])
  • Parameters.
  • $path (string) : Directory path
  • Returns : An array list of files or FALSE on failure
  • Returns type : Array

EXAMPLE

Here is simple example of list files class.

Controller code:-

Your controller code now look like this:-

load->library('ftp');
$config['hostname'] = 'localhost';
$config['username'] = 'root';
$config['password'] = '';
$config['debug']        = TRUE;
$this->ftp->connect($config);
$list = $this->ftp->list_files('filepath to folder');
print_r($list);
$this->ftp->close();
}}
?>

9. Mirror.

Mirror method is used to recreated the orignal path on the server.

mirror($locpath, $rempath)
  • Parameters.
  • $locpath (string) : Local path
  • $rempath (string) : Remote path
  • Returns : TRUE on success, FALSE on failure
  • Returns type : Bool

EXAMPLE

Here is simple example of mirror class.

Controller code:-

Your controller code now look like this:-

load->library('ftp');
$config['hostname'] = 'localhost';
$config['username'] = 'root';
$config['password'] = '';
$config['debug']        = TRUE;
$this->ftp->connect($config);
$this->ftp->mirror('orignal_path', 'recreated_path');
$this->ftp->close();
}}
?>

10. Mkdir.

This method is set octal value in second parameter.

mkdir($path[$permissions = NULL])
  • Parameters.
  • $path (string) : Path to directory to create
  • $permissions (int) : Permissions (octal)
  • Returns : TRUE on success, FALSE on failure
  • Returns type : Bool

EXAMPLE

Here is simple example of mkdir class.

Controller code:-

Your controller code now look like this:-

load->library('ftp');
$config['hostname'] = 'localhost';
$config['username'] = 'root';
$config['password'] = '';
$config['debug']        = TRUE;
$this->ftp->connect($config);
$this->ftp->mkdir('directory_path', 0755);
$this->ftp->close();
}}
?>

11. Close.

This function is used to close connection to the server.

close()
  • $permissions (int) : Permissions (octal)
  • Returns : TRUE on success, FALSE on failure
  • Returns type : Bool

EXAMPLE

Here is simple example of close class.

Controller code:-

Your controller code now look like this:-

$this->ftp->close();

Codeigniter Form Validation Library


Codeigniter Form Validation Library – Codeigniter provides predefined rules to validate the form fields that can be frequently used by loading the validation library. $this->load->library(‘form_validation’); is used to load the library. This library provides the optimized code for the form validation which reduces the effort & time to add the validations in form fields. Here in this tutorial, we are going to explain how to use form validation library.


Codeigniter form validation library | Load | Example

Let us understand how form validation library works in codeigniter with examples.

Load form validation class library

First load form validation library to use its functions, this library can be loaded simply as below-

How to load form validation library:

$this->load->library('form_validation');

Functions:-

There are following functions available in form validation library. Now we will explain one by one with example.

  • 1. Setting validation rules.
  • 2. Setting rules using an array and cascading rules.
  • 3. Prepping data.
  • 4. Re-populating the form.
  • 5. Callbacks: Your own validation methods.
  • 6. Setting error messages.
  • 7. Translating field names.

1. Setting validation rules

This method take three parameters :-

  • The field name.
  • The validation rule for this field
  • Set custom error message for current field(Optional field)

EXAMPLE

Here is simple example of setting validation rules.

Controller code:-

Your controller code now look like this:-

load->view('validation_view');
}
public function index(){
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
   array('required' => 'You must provide a %s.'));
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
 if ($this->form_validation->run() == FALSE)
    {
	$errors = validation_errors();
       $this->session->set_flashdata('error', $errors);
       redirect(base_url('index.php/form_check_controller/check'));	
}else{
    echo "successfully inserted";					
       }}}
?>

Views code:-

Your view code now look like this:-


Username
Password
Password Confirm
Email Address

Output will be like this:-

Codeigniter Form Validation Library

2. Setting rules using an array rule.

EXAMPLE

Here is simple example of Setting rules using an array rule.

Controller code:-

Your controller code now look like this:-

load->view('validation_view');
	}
public function arraycheck()
		{
			$this->load->helper('form');
            $this->load->library('form_validation');
			$array = array(array('field' => 'username',
                'label' => 'Username',
                'rules' => 'required'),
				array('field' => 'password',
                'label' => 'Password',
                'rules' => 'required',
                'errors' => array('required' => 'You must provide a %s.',
                ),),
		array(
                'field' => 'passconf',
                'label' => 'Password Confirmation',
                'rules' => 'required'),
		array(
                'field' => 'email',
                'label' => 'Email',
                'rules' => 'required'
				));
		$this->form_validation->set_rules($array);
		if ($this->form_validation->run() == FALSE)
                {
		$errors = validation_errors();
	        $this->session->set_flashdata('error', $errors);    
		redirect(base_url('index.php/form_check_controller/check'));	
                }
                else
                {
		echo "successfully inserted";					
                }}}
?>

Output will be same like above code:-

3. Prepping data.

EXAMPLE

Here is simple example of Prepping data.

Controller code:-

Your controller code now look like this:-

$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[6]|max_length[15]');
            $this->form_validation->set_rules('password', 'Password', 'required',
                        array('required' => 'You must provide a %s.')
                );
            $this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required|matches[password]');
            $this->form_validation->set_rules('email', 'Email', 'required');

This method is used for checking for length and matching both password fields.

Output will be like this:-

Codeigniter Form Validation Library

4. Re-populating the form.

EXAMPLE

Here is simple example of Re-populating the form.

view code:-

Your view code now look like this:-



Username
Password
Password Confirm
Email Address

This method is used for re-populated your form fields.

Output will be like this:-

Codeigniter Form Validation Library

5. Callbacks: Your own validation methods.

EXAMPLE

Here is simple example of Callbacks: Your own validation methods.

Controller code:-

Your controller code now look like this:-

load->view('validation_view');
}
public function index()
{
$this->load->helper('form');
 $this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
$this->form_validation->set_rules('password', 'Password', 'required',
array('required' => 'You must provide a %s.'));
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required|matches[password]');
$this->form_validation->set_rules('email', 'Email','required');
$check = $this->form_validation->run();
if ($check == FALSE)
{
$errors = validation_errors();
$this->session->set_flashdata('error', $errors);
redirect(base_url('index.php/form_check_controller/check'));	
}
else
{
echo "successfully inserted";					
}}

public function username_check($check)
{
if ($check == '')
{
$this->form_validation->set_message('username_check', 'The {username} field can not be the word "null"');
return FALSE;
}
else
{
return TRUE;
}}}
?>

Output will be like this:-

Codeigniter Form Validation Library

6. Setting error messages.

EXAMPLE

Here is simple example of setting error messages.

Controller code:-

Your controller code now look like this:-

load->view('validation_view');
}
public function index()
 {
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_message('min_length', '{field} must have at least {param} characters.');
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
$this->form_validation->set_rules('password', 'Password', 'rule1|rule2|rule3',
array('rule2' => 'Error Message on rule2 for this field_name'));
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required|matches[password]');
$this->form_validation->set_rules('email', 'Email','required');
$check = $this->form_validation->run();
if ($check == FALSE)
{
$errors = validation_errors();
$this->session->set_flashdata('error', $errors);
redirect(base_url('index.php/form_check_controller/check'));	
}
 else
{
echo "successfully inserted";					
}}}
?>

Output will be like this:-

Codeigniter Form Validation Library

7. Translating field names.

EXAMPLE

Here is simple example of translating field names.

Controller code:-

Your controller code now look like this:-

$this->form_validation->set_rules('username', 'lang:Your_name', 'required');

Output will be like this:-

Codeigniter Form Validation Library

Class reference

There are following types of class reference in form validation library.

1. Set rules.

set_rules($field[$label = ''[$rules = ''[$errors = array()]]])

This function is used to give permits you to set validation rules.

2. run.

run([$group = ''])

this method is used to run validation rules and return always boolean type result.

3. Set message.

set_message($lang[$val = ''])

We use this method for set the custom errors message..

4. Set error delimiters.

set_error_delimiters([$prefix = '

'[$suffix = '

']])

We use this method for set default prefix and suffix errors.

5. Set data.

set_data($data)

this method is used to set an array for validation.

6. Reset validation.

reset_validation()

This function is used to give permits to reset the validation.

7. Error array.

error_array()

This function is used to display error message in array form.

8. Error.

error($field[$prefix = ''[$suffix = '']])

We use this method for return a error message in specific fields.

Codeigniter File Uploading Class Library


Codeigniter File Uploading Class Library – This library provides various functions that are used to give permission of files to be uploaded. We can set many preferences, like type and size of files. $this->load->library(‘upload’); is used to load the library. This library is also equip for check file type and file size. Here in this tutorial, we are going to explain how to use file uploading class library.


Codeigniter file uploading class library | Load | Example

Let us understand how file uploading class works in codeigniter with examples.

Load file uploading class library

First load file uploading library to use its functions, this library can be loaded simply as below-

How to load file uploading class library:

$this->load->library('upload');

class referneces:-

There are following reference in file uploading class.

    • 1. Initialize.
    • 2. Upload
    • 3. Display errors
    • 4. Data

    1. Initialize.

    Syntax of initialize function is

    Syntax of initialize function is:-

    initialize([array $config = array()[$reset = TRUE]])	
    

      Parameters:

    • $config (array) : Preferences
    • $reset (bool) : Whether to reset preferences (that are not provided in $config) to their defaults
    • Returns : CI_Upload instance (method chaining)
    • Return type : CI_Upload

    2. Upload.

    Syntax of Upload function is

    Syntax of Upload function is:-

    do_upload([$field = 'userfile'])	
    

      Parameters:

    • $field (string) : Name of the form field
    • Returns : TRUE on success, FALSE on failure
    • Return type : bool

    3. Display errors.

    Syntax of display errors function is

    Syntax of display errors function is:-

    display_errors([$open = '

    '[$close = '

    ']])

      Parameters:

    • $open (string) : Opening markup
    • $close (string) : Closing markup
    • Returns : Formatted error message
    • Return type : string

    4. Data.

    Syntax of data function is

    Syntax of data function is:-

    data([$index = NULL])	
    

      Parameters:

    • $data (string) : Element to return instead of the full array
    • Returns : Information about the uploaded file
    • Return type : mixed

    EXAMPLE OF FILE UPLOADING

    Controller parts:-

    [File Name = upload_controller.php]:-

    
    load->view('upload_view');
    }
    public function uploadfile()
    {
    $config['upload_path']          = './uploads/';
    $config['allowed_types']        = 'gif|jpg|png';
    $config['max_size']             = 4096;
    $config['max_width']            = 2000;
    $config['max_height']           = 2000;
    $fileName = 'fileToUpload';
    $this->load->library('upload', $config);
    if ( ! $this->upload->do_upload($fileName))
    {
    $error = $this->upload->display_errors($fileName);
    echo $error;
    }
    else
    {
    $data = $this->upload->data();
    $message = "Successfully Uploaded";
    $this->session->set_flashdata('message', $message);
    redirect(base_url('index.php/library/upload_Controller/index'));
    }}}
    ?>
    

    View part:-

    [File Name = upload_view.php]:-

    session->flashdata('message'); ?>


    The output will be like this –

    Selected file

    Codeigniter File Uploading Class Library

    Successfull message

    Codeigniter File Uploading Class Library

    File save location

    Codeigniter File Uploading Class Library

Codeigniter Encrypt Class Library


Codeigniter Encrypt Class Library – This library provides various functions that are used to encription of data. $this->load->library(‘encrypt’); is used to load the library. Here in this tutorial, we are going to explain how to use encrypt class library.


Codeigniter encrypt class library | Load | Example

Let us understand how encrypt class works in codeigniter with examples.

Load encrypt library

First load encrpt library to use its functions, this library can be loaded simply as below-

How to load encrypt class library:

 
$this->load->library('encrypt');

Functions:-

There are following functions available in encrypt class library.

  • 1. Encode
  • 2. Decode
  • 3. Set cipher
  • 4. Set mode

1. Encode

This function performs data enryption and returns string :-

  • Parameters :
  • $string (string) : Data to encrypt.
  • $key (string) : Encryption key.
  • Returns : Encrypted string.
  • Return type : string.

EXAMPLE

Lets see the simple example of encode.

Example of encode library:-

//controller
public function encode()
	{
		$this->load->library('encrypt');
		$string = 'hello user';
                $key = 'super-secret-key';
		$encrypt = $this->encrypt->encode($string, $key);
		echo $encrypt;
	}
Codeigniter Encrypt Class Library

2. Decode

Decode function is used to decrypt an encoded data :-

  • Parameters :
  • $string (string) : String to decrypt.
  • $key (string) : Encryption key.
  • Returns : Plain-text string.
  • Return type : string.

EXAMPLE

Here is the simple example of decode.

Example of decode library:-

//controller
public function decode()
	{
		$this->load->library('encrypt');
		$string = 'x3mQepxqME5O/7vBc78RDOxfjF3UsFoPsE59sSvfAhghGjdEumpBy4Kz4OOw7rqJ0k/+aVpsmNQycYsdxMwODg==';
                $key = 'super-secret-key';
                $decrypt = $this->encrypt->decode($string, $key);
                echo $decrypt;
	}
Codeigniter Encrypt Class Library

3. Set cipher

This function permit you to set Mcrypt cipher :-

  • Parameters :
  • $cipher (int) : Valid php MCrypt cypher constant.
  • Returns : CI_Encrypt instance.
  • Return type : CI_Encrypt.

EXAMPLE

Here is the simple example of set cipher.

Example of set cipher library:-

//controller
public function setcipher()
	{
		$this->load->library('encrypt');
		echo extension_loaded('mcrypt') ? 'Yup' : 'Nope';
	}
Codeigniter Encrypt Class Library

4. Set mode

This function permit you to set Mcrypt mode :-

  • Parameters :
  • $mode (int) : Valid PHP MCrypt mode constant.
  • Returns : CI_Encrypt instance (method chaining).
  • Return type : CI_Encrypt.

EXAMPLE

Here is the simple example of set mode.

Example of set mode library:-

//controller
public function setmode()
	{
		$this->load->library('encrypt');
		$this->encrypt->set_cipher(MCRYPT_RIJNDAEL_128);
		$this->encrypt->set_mode(MCRYPT_MODE_CBC);
		$key = 'mysomekey';
		$foo = $this->encrypt->encode($key);
		echo $foo;
	}
Codeigniter Encrypt Class Library

Codeigniter Email Class Library


Codeigniter Email Class Library – Email class library provide various functions that are used to send email. It can be done by protocal. $this->load->library(’email’); is used to load the library. Here in this tutorial, we are going to explain how to use email class library.

Codeigniter email class library | Load | Example

Let us understand how file email class works in codeigniter with examples.

Load codeigniter email class library

How to load email class library:

 
$this->load->library('email');

Functions:-

There are following functions available in email class library. Now let us go through one by one to understand.

  • 1. Sending email
  • 2. Setting email preferences

1. Sending email

EXAMPLE

Here is simple example of sending email.

Sending email in codeigniter example:-

//Controller
public function sendmail()
{
$this->load->library('email');
$this->load->view('library/email_view');
$from = $this->email->from('sonukr321@gmail', 'sonu kumar');
$to = $this->email->to('sharmasonukr321@gmail.com');
$cc = $this->email->cc('abc@gmail.com');
$bcc = $this->email->bcc('xyz@gmail.com');

$subject = $this->email->subject('Email Test');
$message = $this->email->message('Testing the email class.');

if($this->email->send($from, $to, $cc, $bcc, $subject, $message))
{
	echo "sent succesfully";
}
else
{
	echo "unable to send";
}
}

2. Setting email preferences

EXAMPLE

Here is simple example of setting email preferences.

Setting email preferences in codeigniter example:-

//Controller
$config['protocol'] = 'sendmail';
$config['mailtype'] = 'text';
$config['smtp_timeout'] = '5';
$config['mailpath'] = '/usr/sbin/sendmail';
$config['charset'] = 'iso-8859-1';
$config['wordwrap'] = TRUE;
$this->email->initialize($config);

There are 21 different preferences availables.

Class reference

There are many types of class reference in email class library.

1. From

from($from[$name = ''[$return_path = NULL]])

This function is used to set email address and name of sender.

2. Reply to

reply_to($replyto[$name = ''])

This function is used to set reply to address.

3. To

to($to)

We use this function to set email address of reciever. address can be single or multiple both.

4. CC

cc($cc)

We use this function to set multiple email address of reciever.

5. Subject

subject($subject)

This function is used to set email subject.

6. Message

message($body)

This function is used to set email message body.

7. Set alt message

set_alt_message($str)

This function is used to set alternative email message body.

8. Set header

set_header($header, $value)

This function is used to add additional header.

9. Clear

clear([$clear_attachments = FALSE])

This function is used to clear all attachment files.

10. Send

send([$auto_clear = TRUE])

This method is used to sending the email.

11. Attachment

attach($filename[$disposition = ''[$newname = NULL[$mime = '']]])

We use this function to add multiple attachment files.

12. Print debugger

print_debugger([$include = array('headers', 'subject', 'body')])

By using this function we can print any type of error in email class.

Codeigniter Config Class Library


Codeigniter Config Class Library– Configuration is an important part of any framework, codeigniter provides default configuration file where we can add the application configuration settings. $this->config->load(‘filename’); loads the configuration file. Sometimes we need to create custom configuration file, codeigniter provides an easy way to create custom config files. It is very simple to create custom configuration file in codeigniter. Here in this tutorial we are going to explain with various examples.


Codeigniter config class library | Load | Example

Let us understand how config class works in codeigniter with examples.

Load codeigniter config class library

How to load codeigniter config class library example:

 
$this->config->load('filename');

Where file_name is name of the configuration file that you want to load.

Working with config file :-

Let us understand how to use default configuration file and create own custom configuration file.

How to Create Custom Configuration File?

To create custom config file first go to config folder and create a file named config_custom.php in config folder.

Codeigniter Config Class Library
Codeigniter Config Class Library

You can load config files in following ways-

  • 1. Auto loading : Codeigniter has auto-load function which helps us to load library, helpers and models.
  • 2. Manual loading : We can load config files manually.

Functions:-

Two functions are available in config class library. Now we will explain one by one with example.

  • 1. Fetching config item.
  • 2. Setting a config item.

1. Fetching config items

EXAMPLE

You can fetch the config items simply as below-

How to fetch config items in codeigniter example:-


public function configure()
{
$this->config->load('custom_config');	
echo "Default Value 
"; echo $this->config->item('tutorialsplane_main_url'); }

2. Setting a config item

EXAMPLE

Here is simple example of setting a config item.

Codeigniter set config item value example:-


public function configure()
{
 echo "After Updating Config Value
"; $this->config->set_item('tutorialsplane_main_url', 'tutorialsplane'); echo $this->config->item('tutorialsplane_main_url'); }

Class Reference

There are following types of class reference in config class.

1. Config

$config

This loads all config values.

2. Item

item($item[$index=''])

This rule is used to fetch an item from the configuration file.

3. Set item

set_item($item, $value)

Set Item function sets the value of item.

4. Load

load([$file = ''[, $use_sections = FALSE[, $fail_gracefully = FALSE]]])

Load function is used to load the configuration file.

5. Site Url

site_url()

Site Url function returns the url of your site along with the index.

6. Base Url

base_url()

Base Url function returns url of your site along with optional path like stylesheet or image.

7. System Url

system_url()

System Url function gives url of your codeigniter system/directory.

Codeigniter Shopping Cart Class


Codeigniter Shopping Cart Class– Codeigniter shopping cart class provide various functions that are used to display in a standard shopping cart format and allows user to update and delete from the cart. $this->load->library(‘cart’); is used to load the library. This library serves to create a shopping cart. Here in this tutorial, we are going to explain how to use shopping cart class.


Codeigniter shopping cart class library Example

Let us first see how to load shopping cart class library and then use its function-

Load codeigniter shopping cart class library

How to load shopping cart class library:

Syntax of shopping cart library.:-

 
$this->load->library('cart');

Functions:-

There are following functions available in shopping cart class library. Now we will explain one by one with example.

  • 1. Adding an item to the cart
  • 2. Adding multiple items to the cart
  • 3. Updating the cart
  • 4. Displaying the cart

1. Adding an item to the cart

This function has five reserved indexes :-

  • Id : Every product in your store must have a unique id.
  • Qty : The quantity being purchase.
  • Price : Price of the item.
  • Name : Name of the item.
  • Options : Option are needed to identify the product

EXAMPLE

Here is simple example of adding an item to the cart.

Adding an item to the cart in example:-

//Controller
 '123',
        'qty'     => 1,
        'price'   => 50.95,
        'name'    => 'T-Shirt',
        'options' => array('Size' => 'M', 'Color' => 'Green')
);

echo $this->cart->insert($attributes);
?>

2. Adding multiple items to the cart

This function has also same reserved indexes :-

EXAMPLE

Here is simple example of adding multiple items to the cart.

Adding multiple items to the cart in example:-

//Controller
Adding Multiple Items to The Cart
 'sku_123ABC',
                'qty'     => 2,
                'price'   => 39.95,
                'name'    => 'T-Shirt',
                'options' => array('Size' => 'L', 'Color' => 'Red')
        ),
        array(
                'id'      => 'sku_567ZYX',
                'qty'     => 1,
                'price'   => 9.95,
                'name'    => 'Coffee Mug'
        ),
        array(
                'id'      => 'sku_965QRS',
                'qty'     => 85,
                'price'   => 29.95,
                'name'    => 'Shot Glass'
        )
);

echo $this->cart->insert($multiple);
?>

3. Updating the cart

EXAMPLE

Here is simple example of updating the cart.

Updating the cart in example:-

//Controller

Updating The Cart

'abcd12345', 'qty' => 5 ); ?>

4. Displaying the cart

EXAMPLE

Let us create a simple example to display the cart data.

Displaying the cart in example:-

//Controller

Displaying The Cart

cart->contents() as $items): ?>
Quantity Material Description Material Price Sub-Total
$i.'[qty]', 'value' => $items['qty'], 'maxlength' => '3', 'size' => '5')); ?> cart->has_options($items['rowid']) == TRUE): ?>

cart->product_options($items['rowid']) as $option_name => $option_value): ?> :

cart->format_number($items['price']); ?> $cart->format_number($items['subtotal']); ?>
Total $cart->format_number($this->cart->total()); ?>

The output will be like this :–

Class reference

There are many types of class reference in shopping class.

1. Product id rules

$product_id_rules = '.a-z0-9_-'

This rule is used to validate the product ID like:- alpha-numeric, dashes, underscores.

2. Product name rules

$product_name_rules = 'w -.:'

This rule is used to validate the product ID and Product Name like:- alpha-numeric, dashes, underscores.

3. Insert data

insert([$items = array()])

This rule is used to insert item details and save it to session table. Its always return boolean type.

4. Update data

update([$items = array()])

We can be used this function to update property of given item. Its also return boolean return type.

5. Remove data

remove($rowid)

This function is used to delete any particular row from the shopping cart.

6. Total

total()

It is used to display total amount of your shopping cart.

7. Total items

total_items()

It is used to display total number of item in shopping cart.

8. Destroy

destroy()

This function is used to destroy the shopping cart.

Codeigniter Calendaring Class Library


Codeigniter Calendaring Class Library – Calendaring class library provide various functions that are used to create dynamically calendars. $this->load->library(‘calendar’); is used to load the library. This library serves to display and generate a calendar. Here in this tutorial, we are going to explain how to use calendaring class library.


Codeigniter calendaring class library.

Let us first see how to load calendaring class library and then use its function-

Load codeigniter calendaring class library

How to load calendaring class library:

Syntax of how to load this library.:-

 
$this->load->library('calendar');

Functions:-

There are following functions available in calendaring class library. Now we will explain one by one with example.

  • 1. Displaying a calendar
  • 2. Passing data to your calendar
  • 3. Setting display preferences
  • 4. Show next/previous month link
  • 5. Creating a calendar template

1. Displaying a calendar

Syntax of displaying a calendar is

Syntax of displaying a calendar is:-

generate([$year = ''[$month = ''[$data = array()]]])
$this->calendar->generate();

Parameters :-

  • $year (int) : Year
  • $month (int) : Month
  • $data (array) : Data to be shown in the calendar cells
  • Returns : HTML-formatted calendar
  • Return type : String

EXAMPLE

Here is simple example of displaying a calendar.

Displaying a calendar in codeigniter Example:-

//Controller
public function displaycalendar()
	{
		$this->load->library('calendar');
		echo $this->calendar->generate();	
	}

The output will be like this –

Codeigniter Calendaring Class library

2. Passing data to your calendar

EXAMPLE

Here is simple example of passing data to your calendar.

Passing data to your calendar in codeigniter example:-

//Controller
public function passingcalendar()
	{
		$this->load->library('calendar');
		$data = array 
		(
        2  => 'http://example.com/news/article/2017/03/02/',
        10  => 'http://example.com/news/article/2017/03/10/',
        17 => 'http://example.com/news/article/2017/03/17/',
        28 => 'http://example.com/news/article/2017/03/28/'
         );
         echo $this->calendar->generate(2017, 3, $data);   	
	}

The output will be like this –

Codeigniter Calendaring Class library

3. Setting display preferences

EXAMPLE

Here is simple example of setting display preferences.

Setting display preferences in codeigniter example:-

//Controller
public function setdisplay()
	{
		$attributes = array(
		'start_day'    => 'monday',
		'month_type'   => 'long',
		'day_type'     => 'short'
	);

	$this->load->library('calendar', $attributes);

	echo $this->calendar->generate();
	}

The output will be like this –

Codeigniter Calendaring Class library

4. Show next/previous month link

EXAMPLE

Here is simple example of show next/previous month link.

Show next/previous month link in codeigniter example:-

//Controller
public function showmonth()
	{
	$attributes = array('show_next_prev'  => TRUE,
        'next_prev_url'   => 'http://localhost/index.php/calendar/show/');
        $this->load->library('calendar', $attributes);
        echo $this->calendar->generate();	
	}

The output will be like this –

Codeigniter Calendaring Class library

5. Creating a calendar template

EXAMPLE

Here is simple example of creating a calendar template.

Creating a calendar template in codeigniter example:-

//Controller
public function temp()
	{
		$attributes['template'] = array
		(
        'table_open'           => '',
        'cal_cell_start'       => '
', 'cal_cell_start_today' => '' ); $this->load->library('calendar', $attributes); echo $this->calendar->generate();

The output will be like this –

Class reference

There are following types of class reference in calendar classes.

1. Initialize

initialize([$config = array()])

This function is used to initialize the calendar preferences and containing display preferences.

2. Generate calendar

generate([$year = ''[$month = ''[$data = array()]]])

This function is used to generate the calendar.

3. Month name

get_month_name($month)

This function is used to generate text month name based on numeric month provider.

4. Day name

adjust_date($month, $year)
//like this
print_r($this->calendar->adjust_date(13, 2014));

This function is used to make sure that you have valid month/year.

5. Get total day

get_total_days($month, $year)
//like this
echo $this->calendar->get_total_days(7, 2017);

This function count total days of specific month.