Showing posts with label Codeigniter Session Storage. Show all posts
Showing posts with label Codeigniter Session Storage. Show all posts

Codeigniter Ajax dropdown

Codeigniter Ajax dropdown


Codeigniter ajax dropdown Codeigniter Framework Lot of task previously discussed. Today discussed Codeigniter dropdown ajax how to implemented. Similarly Codeigniter ajax Pagination  
Codeigniter Ajax dropdown
Codeigniter Ajax dropdown

Dropdown City and Country Used Ajax


Controller
<?php

class User extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('country_model');
    }

    public function index() {
        $this->load->view('register');
    }

    public function register() {
        $data['countries'] = $this->country_model->get_countries();
        $this->load->view('post_view', $data);
    }

    public function get_cities($country) {
        $this->load->model('city_model');
        header('Content-Type: application/x-json; charset=utf-8');
        echo(json_encode($this->city_model->get_cities($country)));
    }

}
City_Model
<?php

class City_model extends CI_Model {

    public function __construct() {
        $this->load->database();
    }

    function get_cities($country = null) {
        $this->db->select('id, city_name');

        if ($country != NULL) {
            $this->db->where('country_id', $country);
        }

        $query = $this->db->get('cities');
        $cities = array();

        if ($query->result()) {
            foreach ($query->result() as $city) {
                $cities[$city->id] = $city->city_name;
            }
            return $cities;
        } else {
            return FALSE;
        }
    }

}
?>

Country_Model

<?php

class Country_model extends CI_Model {

    public function __construct() {
        $this->load->database();
    }

    function get_countries() {
        $this->db->select('id, country_name');
        $query = $this->db->get('countries');
        echo "countries";
        $countries = array();

        if ($query->result()) {
            foreach ($query->result() as $country) {
                $countries[$country->id] = $country->country_name;
            }
            return $countries;
        } else {
            return FALSE;
        }
    }

}
?>

View
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script type="text/javascript">// <![CDATA[
            $(document).ready(function() {
                $('#country').change(function() { //any select change on the dropdown with id country trigger this code
                    $("#cities > option").remove(); //first of all clear select items
                    var country_id = $('#country').val(); // here we are taking country id of the selected one.
                    $.ajax({
                        type: "POST",
                        url: "http://localhost/task/user/get_cities/" + country_id, //here we are calling our user controller and get_cities method with the country_id

                        success: function(cities) //we're calling the response json array 'cities'
                        {
                            $.each(cities, function(id, city) //here we're doing a foeach loop round each city with id as the key and city as the value
                            {
                                var opt = $('<option />'); // here we're creating a new select option with for each city
                                opt.val(id);
                                opt.text(city);
                                $('#cities').append(opt); //here we will append these new select options to a dropdown with the id 'cities'
                            });
                        }

                    });

                });
            });
            // ]]>
        </script>
    </head>
    <body>
        <?php $countries['#'] = 'Please Select'; ?>

        <label for="country">Country: </label><?php echo form_dropdown('country_id', $countries, '#', 'id="country"'); ?><br />
        <?php $cities['#'] = 'Please Select'; ?>
        <label for="city">City: </label><?php echo form_dropdown('city_id', $cities, '#', 'id="cities"'); ?><br />
    </body>
</html>


Prevent SQL injection in Codeigniter (CI)

Prevent SQL injection in Codeigniter (CI)


SQL injection is an attack made on database query.  In PHP, we are use mysql_real_escape_string()
function to prevent this along with other techniques but codeigniter provides inbuilt function and libraries to prevent this.Join Queries

Prevent SQL injection in Codeigniter (CI)
Prevent SQL injection in Codeigniter (CI)


We can prevent SQL Injection in CodeIgniter in the following three ways  

Escaping Queries
Query Biding
Active Record Class



Escaping Queries
<?php
$name = $this->input->post('uname');
$cn = 'SELECT * FROM tbl_users WHERE user_name='.$this->db->escape($name);
$this->db->query($cn);
?> 
Here $this->db->escape() determines the data type so that it can escape only string data.
It also automatically adds single quotes around the data so you don’t have to do that as well.

Preventing SQL injection in Codeigniter using Query Binding Method 

<?php
    $sql = "SELECT * FROM subscribers_tbl WHERE status = ? AND email= ?";
    $this->db->query($sql, array('active', 'dev2tricks.com.in'));
?>
The query are automatically replaced with the values in the array in the second parameter of the query function.

in Query Binding Method, you don’t have to escape the values manually as it will automatically do that for you.


Preventing SQL injection in Codeigniter using Active Record Class

<?php
   $this->db->get_where('subscribers_tbl',array('status' => 'active','email' => 'dev2tricks.com.in'));
?>

Codeigniter PDF File Upload

Codeigniter PDF File Upload


PDF File Upload Codeigniter Framework mostly discussed previously and this post is about uploading files in Codeigniter has upload library by using this class we can upload file on server very easily. Codeigniter session Storage

Codeigniter PDF File Upload
Codeigniter PDF File Upload


<?php
echo $error;
echo form_open_multipart('upload/do_upload');
echo form_input(array('type' => 'file','name' => 'userfile'));
echo form_submit('submit','upload');
echo form_close();
?>

Controller method you need to set some config setting like uploading path, allowed types, upload sizes, width height,... etc.

    function upload(){
        $this->load->library('upload');   
        $config['upload_path'] = './assets/certificates/';
        $config['allowed_types'] = 'pdf';
        $config['max_size']    = '1000000';
        $config['file_name'] = "upload";

        $this->upload->initialize($config);
        $certificateflag = $this->upload->do_upload("certificate");       
        if ($this->upload->do_upload("certificate"))
            error_reporting(E_ALL);
        else{
            echo "<pre>"; Print_r($this->upload->data()); echo "</pre>";
        }
}<?php

Library Codeigniter PDF File upload root directory Follows


Open <root_directory>/system/application/config/mimes.php file

Change value of ‘pdf’ element of $mimes array

$mimes = array( ‘hqx’   =>      ‘application/mac-binhex40’,
‘cpt’   =>      ‘application/mac-compactpro’,
‘csv’   =>      array(‘text/x-comma-separated-values’, ‘text/comma-separated-values’, ‘application/octet-stream’, ‘application/vnd.ms-excel’, ‘text/csv’, ‘application/csv’, ‘application/excel’, ‘application/vnd.msexcel’),
‘bin’   =>      ‘application/macbinary’,
‘dms’   =>      ‘application/octet-stream’,
‘lha’   =>      ‘application/octet-stream’,
‘lzh’   =>      ‘application/octet-stream’,
‘exe’   =>      ‘application/octet-stream’,
‘class’ =>      ‘application/octet-stream’,
‘psd’   =>      ‘application/x-photoshop’,
‘so’    =>      ‘application/octet-stream’,
‘sea’   =>      ‘application/octet-stream’,
‘dll’   =>      ‘application/octet-stream’,
‘oda’   =>      ‘application/oda’,
‘pdf’   =>      array(‘application/pdf’, ‘application/x-pdf’),

To

‘pdf’   =>      array(‘application/pdf’, ‘application/x-pdf’, ‘application/x-download’,’application/x-download’, ‘binary/octet-stream’, ‘application/unknown’, ‘application/force-download’),

Codeigniter Ajax Pagination


Codeigniter Ajax Pagination

Codeigniter Ajax Pagination today solve this task so just share with your. Today we will discuss how to create ajax pagination in Codeigniter Framework. Codeigniter have the pagination library by default.  But many times we are needed to implemented ajax based pagination in codeigniter. and pagination responsive design you implemented your own designed.

Already we discussed codeigniter framework and other related topics so just go the task at first we need to add ajax pagination into the Codeigniter Pagination library.  Copy the Codeigniter pagination library and modify with ajax pagination code.  Rename the Pagination Class to Ajaxpagination and insert the Ajaxpagination.php file into the library folder.  you can download the CodeIgniter Ajax pagination library from the Click Here

   
Codeigniter Ajax Pagination
Codeigniter Ajax Pagination
First Create table


CREATE TABLE `dent_adminusers` (
  `id` int(11) NOT NULL auto_increment,
  `adminname` varchar(50) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL,
  `status` enum('Active','Suspend','Deactive') NOT NULL default 'Deactive',
  `mailstatus` enum('0','1') NOT NULL default '0',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

Controller

Create a controller file named posts.php with Posts classed. Into the __construct() function we need to load post model.  Ajaxpagination library. And we set the per page data limit into the $this-perPage variable.


<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Posts Management class created by CodexWorld
 */
class Posts extends CI_Controller {
    
    function __construct() {
        parent::__construct();
        $this->load->model('post');
        $this->load->library('Ajaxpagination');
        $this->perPage = 1;
    }
    
    public function index()
    {
        $data = array();
        
        //total rows count
        $totalRec = count($this->post->getRows());
        
        //pagination configuration
        $config['first_link']  = 'First';
        $config['div']         = 'postList'; //parent div tag id
        $config['base_url']    = base_url().'posts/ajaxPaginationData';
        $config['total_rows']  = $totalRec;
        $config['per_page']    = $this->perPage;
        
        $this->ajax_pagination->initialize($config);
        
        //get the posts data
        $data['posts'] = $this->post->getRows(array('limit'=>$this->perPage));
        
        //load the view
        $this->load->view('posts/index', $data);
    }
    
    function ajaxPaginationData()
    {
        $page = $this->input->post('page');
        if(!$page){
            $offset = 0;
        }else{
            $offset = $page;
        }
        
        //total rows count
        $totalRec = count($this->post->getRows());
        
        //pagination configuration
        $config['first_link']  = 'First';
        $config['div']         = 'postList'; //parent div tag id
        $config['base_url']    = base_url().'posts/ajaxPaginationData';
        $config['total_rows']  = $totalRec;
        $config['per_page']    = $this->perPage;
        
        $this->ajax_pagination->initialize($config);
        
        //get the posts data
        $data['posts'] = $this->post->getRows(array('start'=>$offset,'limit'=>$this->perPage));
        
        //load the view
        $this->load->view('posts/ajax-pagination-data', $data, false);
    }
}


Model:

Codeigniter Ajax Pagination Create a Model file follows Code.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Post extends CI_Model{
    
    function __construct() {
        $this->postTable = 'posts';
    }
    
    function getRows($params = array())
    {
        $this->db->select('*');
        $this->db->from($this->postTable);
        $this->db->order_by('created','desc');
        
        if(array_key_exists("start",$params) && array_key_exists("limit",$params)){
            $this->db->limit($params['limit'],$params['start']);
        }elseif(!array_key_exists("start",$params) && array_key_exists("limit",$params)){
            $this->db->limit($params['limit']);
        }
        
        $query = $this->db->get();
        
        return ($query->num_rows() > 0)?$query->result_array():FALSE;
    }
}
?>


View

Codeigniter Ajax Pagination responsive or your design modify view page.


<h1>Posts</h1>
<div id="container">
    <ul class="list" id="postList">
        <?php if(!empty($posts)): foreach($posts as $post): ?>
        <li>
            <p><b>Title:</b>&nbsp;<?php echo $post['title']?></p>
            <p><b>Content:</b>&nbsp;<?php echo $post['content']?></p>
            <p><b>Created:</b>&nbsp;<?php echo $post['created']?></p>
        </li>
        <?php endforeach; else: ?>
        <li class="err_msg">Post(s) not available.</li>
        <?php endif; ?>
        <?php echo $this->ajax_pagination->create_links(); ?>
    </ul>
</div>

How to send email with CodeIgniter

How to send email with CodeIgniter


How to send email with CodeIgniter
How to send email with CodeIgniter
Today I have solve this task share with you codeigniter Mail Function Send a Mail I am  First time Implementing MVC Structure.  Following Code. Session Storage



View.html

<form action="<?php echo base_url('index.php/email/mysend_mail'); ?>" method="post">
Please, enter e-mail: <input type="text" name="e-mail"><input type="submit" name="submit" value="Submit">
</form>

Controller

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

class Email extends CI_Controller {

  public function __construct(){
    parent::__construct();
    $this->load->helper('url');
  }

public function index()
{

$this->load->view('header');
    $this->load->view('email_form');
    $this->load->view('footer');
}
  
  public function mysend_mail(){
    $this->load->helper('url');

    if (!isset($_POST['e-mail'])){
      //redirect if no parameter e-mail
      redirect(base_url());
    };

    //load email helper
    $this->load->helper('email');
    //load email library
    $this->load->library('email');
    
    //read parameters from $_POST using input class
    $email = $this->input->post('e-mail',true);    
  
    // check is email addrress valid or no
    if (valid_email($email)){  
      // compose email
      $this->email->from($email , 'xxxxx');
      $this->email->to($email); 
      $this->email->subject('My First CodeIgniter Email Example');
      $this->email->message('CodeIgniter Email Example App!');  
      
      // try send mail ant if not able print debug
      if ( ! $this->email->send())
      {
        $data['message'] ="Email not sent \n".$this->email->print_debugger();      
        $this->load->view('header');
        $this->load->view('message',$data);
        $this->load->view('footer');

      }
         // successfull message
        $data['message'] ="Email was successfully sent to $email";
      
        $this->load->view('header');
        $this->load->view('message',$data);
        $this->load->view('footer');
    } else {

      $data['message'] ="Email address ($email) is not correct. Please <a href=".base_url().">try again</a>";
      
      $this->load->view('header');
      $this->load->view('message',$data);
      $this->load->view('footer');
    }

  }
  
  public function info(){
    phpinfo();
  }
    
}

Codeigniter Session Storage

Codeigniter Session Storage


Codeigniter Session Storage
Codeigniter Session Storage
Codeigniter Session Storage is Very simpley and easly storage Login authentication  Username stored session. Codeigniter Login form
using this code:

$this->session->set_userdata() 

I just found that setting sess_encrypt_cookie to FALSE fixed the chrome logout issue.

Session Storage Config settings following Code.

$config['sess_encrypt_cookie'] = FALSE

$config['sess_match_useragent'] = FALSE;

$config['sess_expiration'] = 8600;


$this->session->set_userdata('user_session', $user_session_data);

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

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

Model

 function Login($email,$pass){
         $this->db->where('username' ,$email);
         $this->db->where('password',$pass);
         $query=$this->db->get('users');  
     if ($query->num_rows == 1) {        
    return true;  
     }    
     return FALSE;
    }

Controller:

   function varification(){
            $this->load->model('login_model');
    $email=$this->input->post('email');
    $pass=$this->input->post('pass');
    $success=$this->login_model->Login($email,$pass);
    if ($success) {
                 $data = array(
                       'user_name' => $rows->username,
                       'logged_in' => TRUE,
                      'validated' => true
                 );
                $this->session->set_userdata($data);
                redirect ('site/index');
    } else{ // incorrect id or password
             redirect ('site/login');
            }
    }