How to set cookie in codeigniter

Leave a Comment

Cookies in codeigniter



To use cookies in codeigniter we have to use its helper class.The Cookie Helper file contains functions that assist in working with cookies.
Below is the example to set cookies in get its values.So we create controller cookies_demo.php.Add the some method like the below example:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class cookies_demo extends CI_Controller {
 
 function __construct()
 {
  parent::__construct();
  $this->load->helper('cookie');
 }
 // to set cookies 
 function set()
 {
  $cookie= array(
      'name'   => 'demo',
      'value'  => 'Hello i m cookies which saved in this broswer',
       'expire' => '86500',
  );
  $this->input->set_cookie($cookie);
  echo "cookies successfully set";
 }
 // to get cookies
 function get()
 {
  echo $this->input->cookie('demo',true);
 }
}



Loading this Helper
This helper is loaded using the following code:
$this->load->helper('cookie');


The following functions are available:

$this->input->set_cookie()

Sets a cookie containing the values you specify. There are two ways to pass information to this function so that a cookie can be set: Array Method, and Discrete Parameters:

Array Method



Using this method, an associative array is passed to the first parameter:
$cookie = array(
    'name'   => 'demo',
      'value'  => 'Hello i m cookies which saved in this broswer',
       'expire' => '86500',
    'domain' => '.only4ututorials.blogspot.com',
    'path'   => '/',
    'prefix' => 'myprefix_',
    'secure' => TRUE
);

$this->input->set_cookie($cookie);


Notes:

  • Only the name and value are required. To delete a cookie set it with the expiration blank.
  • The expiration is set in seconds, which will be added to the current time. Do not include the time, but rather only the number of seconds from now that you wish the cookie to be valid. If the expiration is set to zero the cookie will only last as long as the browser is open.
  • For site-wide cookies regardless of how your site is requested, add your URL to the domain starting with a period, like this: .your-domain.com
  • The path is usually not needed since the function sets a root path.
  • The prefix is only needed if you need to avoid name collisions with other identically named cookies for your server.
  • The secure boolean is only needed if you want to make it a secure cookie by setting it to TRUE.
If after all this your cookies not set.Then check belows Points.

  • If you set 'secure' => TRUE.  which is only for https.
  • Always try to set 'expire' => 'something'.


Discrete Parameters
If you prefer, you can set the cookie by passing data using individual parameters:
$this->input->set_cookie($name, $value, $expire, $domain, $path, $prefix, $secure);



$this->input->cookie()
Lets you fetch a cookie. The first parameter will contain the name of the cookie you are looking for (including any prefixes):
$this->input->cookie('demo',true);

The function returns FALSE (boolean) if the item you are attempting to retrieve does not exist. The second optional parameter lets you run the data through the XSS filter. It's enabled by setting the second parameter to boolean TRUE;



Helpful links




Please comment down below if you have any query and please follows us for more awesome tutorials and keep motivating us .

CodeIgniter From Scratch : Select records from database

Leave a Comment

Select records from database for CodeIgniter CRUD



In previous tutorials we learn how to set up out project directory for codeigniter crud.In this we learn how to fetch data from database using MVC of codegniter.
Let's go to our controller i.e. data.php and add some stuff to make CRUD work. Add the some method like the below example:


<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class data extends CI_Controller {
 
 function __construct()
 {
  parent::__construct();
  //load the  model
  $this->load->model('mdl_data');
 }
 // load the view and fetch data from out model function
 public function index()
 {
  $arrData['users'] = $this->mdl_data->getall(); //call the mdl_data getall function to getall data
  $this->load->view('show',$arrData); // pass all data to view
 }
}



Now let's create out model file which place inside application/model/ name as mdl_data.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Mdl_data extends CI_Model {

 function __construct()
 {
  parent::__construct();
 }
 
 function getall(){
  $query =$this->db->get('users'); //users is the table name
  if($query->num_rows()>0){
   return $query->result_array();  // this will return all data into array
  }
 }
}
Now let's create our view The results that we have seen we can use them to have Codeigniter CRUD. We just need a view to do it. So a view will look like this:
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>CRUD In CodeIgniter</title>
 <style type="text/css">
 .warpper{
  width: 100%;
 }
 .warpper table{
  margin: 50px auto;
  text-align: center;
 }
 .warpper p{
  margin: 50px auto;
 }
 h1{
  text-align: center;
 }
 </style>
</head>
<body>
 <div class="warpper">
  <h1>CRUD In CI</h1>
  <?php if($this->session->flashdata('success')){ ?> 
   <p style="color:green"><?php echo $this->session->flashdata('success'); ?></p>
  <?php } ?>
  <table border=1 cellpadding=5 cellspaceing=5>
   <tr colspan="6"><td><a href="<?php echo base_url()."data/add/"; ?>">Add New Record</a></td></tr>
   <tr>
    <th>Id</th>
    <th>Name</th>
    <th>Email Id</th>
    <th>Edit</th>
    <th>Delete</th>
   </tr>
   <?php if($users) { foreach ($users as $user) { ?>
   <tr>
    <td><?php echo $user['id']; ?></td>
    <td><?php echo $user['name']; ?></td>
    <td><?php echo $user['email_id']; ?></td>
    <th><a href="<?php echo base_url()."data/edit/".$user['id']; ?>">Edit</a></th>
    <th><a href="<?php echo base_url()."data/delete/".$user['id']; ?>">Delete</a></th>
   </tr>
   <?php } } ?>
  </table>
 </div>
</body>
</html>



After doing all this run the code like this http://localhost/crud/data/.So a it will look like this:



CodeIgniter From Scratch : Directory Setup for CRUD

Leave a Comment

Directory Setup And Database Setup For CodeIgniter CRUD.


Step 1: Download Codeigniter and check this Link to set up codeigniter
After Proper Setup Your Page get look like this as seen below



Step 2: Now we are ready to configure our database for our codeigniter project.To do that goto your codeigniter /appication/config/database.php.Open that file in your editor it will look like this.
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| DATABASE CONNECTIVITY SETTINGS
| -------------------------------------------------------------------
| This file will contain the settings needed to access your database.
|
| For complete instructions please consult the 'Database Connection'
| page of the User Guide.
|
| -------------------------------------------------------------------
| EXPLANATION OF VARIABLES
| -------------------------------------------------------------------
|
| ['hostname'] The hostname of your database server.
| ['username'] The username used to connect to the database
| ['password'] The password used to connect to the database
| ['database'] The name of the database you want to connect to
| ['dbdriver'] The database type. ie: mysql.  Currently supported:
     mysql, mysqli, postgre, odbc, mssql, sqlite, oci8
| ['dbprefix'] You can add an optional prefix, which will be added
|     to the table name when using the  Active Record class
| ['pconnect'] TRUE/FALSE - Whether to use a persistent connection
| ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.
| ['cache_on'] TRUE/FALSE - Enables/disables query caching
| ['cachedir'] The path to the folder where cache files should be stored
| ['char_set'] The character set used in communicating with the database
| ['dbcollat'] The character collation used in communicating with the database
|     NOTE: For MySQL and MySQLi databases, this setting is only used
|      as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7
|     (and in table creation queries made with DB Forge).
|      There is an incompatibility in PHP with mysql_real_escape_string() which
|      can make your site vulnerable to SQL injection if you are using a
|      multi-byte character set and are running versions lower than these.
|      Sites using Latin-1 or UTF-8 database character set and collation are unaffected.
| ['swap_pre'] A default table prefix that should be swapped with the dbprefix
| ['autoinit'] Whether or not to automatically initialize the database.
| ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections
|       - good for ensuring strict SQL while developing
|
| The $active_group variable lets you choose which connection group to
| make active.  By default there is only one group (the 'default' group).
|
| The $active_record variables lets you determine whether or not to load
| the active record class
*/

$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = '';
$db['default']['password'] = '';
$db['default']['database'] = '';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;


/* End of file database.php */
/* Location: ./application/config/database.php */


you have change some filed i.e
$db['default']['hostname'] = 'localhost';  // change it with your host name
$db['default']['username'] = 'root';       // change it with your username
$db['default']['password'] = 'root';       // change it with your password
$db['default']['database'] = 'crud_database'; // change it with your DB name
$db['default']['dbdriver'] = 'mysql';                   


After that goto your mysql server phpmyadmin create a new database using this query
Create Database crud_database;     // change it with your database name


Create your table in your database. Let's say we have the table with table name users. The SQL code that you can insert is:
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `email_id` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `name`, `email_id`) VALUES
(1, 'mohit jain', 'mohitj475@gmai.com');
Let's go to the next step.

Step 3: Setup directory for the our CodeIgniter CRUD.

Step 4: Open the autoload.php file i.e. in application/config/autoload.php.

/*
| -------------------------------------------------------------------
|  Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in the system/libraries folder
| or in your application/libraries folder.
|
| Prototype:
|
|	$autoload['libraries'] = array('database', 'session', 'xmlrpc');
*/

$autoload['libraries'] = array('database','session');


/*
| -------------------------------------------------------------------
|  Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|
|	$autoload['helper'] = array('url', 'file');
*/

$autoload['helper'] = array('url');


Autoload the our libraries and helper which we use in this Codeigniter crud.
Powered by Blogger.