Codeigniter Tutorials
- What is codeigniter?
- Application_Architecture
- MVC Architecture
- HMVC Architecture
- Codeigniter Configuration
- Remove index.php from url in codeigniter
- MVC Concept
- View
- Alternate PHP Syntax for View Files
- Routing
- Codeigniter URL
- Get Current URL
- Previous page URL get
- Seo Friendly URL
- Slug Create in codeigniter
- What is _remap() function
- Remove controller name from url in codeigniter
- Codeigniter Controller Class
- Class Constructor
- GET $ POST method in Codeigniter
- Models
- Basepath, Apppath, FCPATH
- URI Segment
- Page Redirect
- Helper class
- Custom Helper class
- Form Helper
- Common Helper Functions
- Common Function
- Array Problems
- Call controller in Helper
- Add active class to menu using Helper class
- Custom Library
- Custom Library Example
- when to use get_instance()
- Codeigniter Hook
- how to work inline css in codeigniter
- Custom 404 page
- 404 custom error page
- Create custom config file in codeigniter
- How to set and get config item value
- How to Speed Up CodeIgniter App?
- Codeigniter Functions
- Session
- cookies
- How to Set & Get Tempdata in Codeigniter
- flash messages in Codeigniter
- Flashdata
- Encryption and Decryption In CodeIgniter
- Codeigniter security
- csrf token form security
- Password Hashing
- Form Validation
- Custom Validation
- Registration Form with validation
- Server Side Form Validation
- Validate Select Option Field
- Date Format Validation
- Date Format change in codeigniter
- Date Functions
- DOB Validation
- CI CRUD
- User SignUp
- User Login
- User Logout
- Login Account
- Login form with RememberMe
- Login Form with session
- User change password
- Change Password with Callback Validation to Check Old Password
- Forgot password
- Reset password
- Insert data in database
- Fetch data from database
- Update data in database
- Delete data in database
- File Upload
- Image Upload with resize Image
- Upload Multiple file and images
- Upload Multiple images with CRUD
- File and image update
- Upload Image Using Ajax.
- Email Send
- Email Send Using Email library
- Email Send Using SMTP Gmail
- Notification send
- store data in json format in DB
- Json parse
- Fetch data Using Ajax with Json data
- How to Show data Using Ajax with Json parse
- Get JSON Data from PHP Script using jQuery Ajax
- Insert data Using Ajax
- Submit data Using Ajax with form validation
- How to show data Using Ajax in codeigniter
- Insert & Update Using Ajax
- Registration Form With Validation Using Ajax in codeigniter
- Delete data Using Ajax Confirmation
- Delete All data Using checkbox selection
- Ajax CSRF Token
- Ajax Post
- Ajax serverside form validation
- Contact form using AJAX with form validation
- DataTable Using Ajax dynamically
- DataTables pagination using AJAX with Custom filter
- DataTables AJAX Pagination with Search and Sort in codeigniter
- DataTables in Codeigniter using Ajax
- Ajax Custom Serarch
- Ajax Live Data Search using Jquery PHP MySql
- Ajax Custom Serarch and sorting in datatable
- Dynamic Search Using Ajax
- Autocomplete using jquery ajax
- Jquery Ajax Autocomplete Search using Typeahead
- Dynamic Dependent Dropdown Using Ajax
- Dynamic Dependent Dropdown list Using Ajax
- Dynamic Dependent Dropdown in codeigniter using Ajax
- ajax username/email availability check using JQuery
- Check Email Availability Using Ajax
- Data Load on mouse scroll
- Ajax CI Pagination
- Pagination in codeigniter
- Ajax Codeigniter Pagination
- email exists or not using ajax with json
- CRUD using AJAX With Modal popup in CI
- Add / Show Data on modal popup using Ajax
- Modal popup Validation using Ajax
- Data show on Modal popup Using Ajax
- Add / Remove text field dynamically using jquery ajax
- How to Add/Delete Multiple HTML Rows using JavaScript
- Delete Multiple Rows using Checkbox
- Multiple Checkbox value
- Form submit using jquery Example
- REST & SOAP API
- Multi-Language implementation in CodeIgniter
- How to pass multiple array in view
- Captcha
- create zip file and download
- PhpOffice PhpSpreadsheet Library (Export data in excel sheet)
- data export in excel sheet
- Excel File generate in Codeigniter using PHPExcel
- Dompdf library
- tcpdf library
- Html table to Excel & docs download
- CI Database Query
- Database Query
- SQL Injection Prevention
- Auth Model
- Join Mysql
- Tree View in dropdown option list
- OTP Integration in codeigniter
- curl post
- download file using curl
- Sweet Alert
- Sweet alert Delete & Success
- Log Message in Codeigniter
- Menu & Submenu show dynamically
- Set Default value in input box
- Cron Jobs
- Stored Procedure
- Display Loading Image when AJAX call is in Progress
- Send SMS
- IP Address
- Codeigniter Tutorialspoint
- Website Link
- How To Create Dynamic Xml Sitemap In Codeigniter
- Paypal Payment Integration
- Get Latitude and Longitude From Address in Codeigniter Using google map API
- How To Create Simple Bar Chart In Codeigniter Using AmCharts?
- dynamic Highcharts in Codeigniter
- Barcode in Codeigniter
- Codeigniter Interview Questions
- Project
Codeigniter Session
session maintain user's "state" and to track their activity when they visit your website.
To use this class you need to first initialize or load the session library of CodeIgniter in your controller constructors or you can also go for $autoload in config file, so that it can be auto-loaded by the system.
To load session library manually use below code – Syntax:
// load your session library in class constructor
$this->load->library('session');
OR
// you can add session library in autoload config file.
$autoload['libraries'] = array('session');
After loading the session library, you can simply use the session object as shown below.
$this->session
Add Session Data
$this->session->set_userdata('key', 'value');
set_userdata() function takes two arguments. The first argument, key, is the name of the session variable, under which, value will be stored.
set_userdata() function also supports another syntax in which you can pass array to store values as shown below.
$newdata = array(
'username' => 'mahtab',
'email' => 'mahtab.habib@itechtuto.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
OR
$this->session->set_userdata('name', 'Your Name');
or
$this->session->set_userdata([
'name' => 'Your Name',
'email' => 'Your Email'
]);
If you want to add userdata one value at a time, set_userdata() also supports this syntax:
$this->session->set_userdata('key', 'value');
If you want to verify that a session value exists, simply check with isset():
// returns FALSE if the 'key' item doesn't exist or is NULL,
// TRUE otherwise:
isset($_SESSION['key'])
Or you can call has_userdata():
$this->session->has_userdata('key');
Fetch Session Data
After setting data in session, we can also retrieve that data as shown below. Userdata() function will be used for this purpose. This function will return NULL if the data you are trying to access is not available.
$name = $this->session->userdata('username');
OR
// Get all session data
$this->session->userdata();
How to print All Session Data
File Name :
print_r($_SESSION);
Remove Session Data
unset_userdata() function will remove only one variable from session.
File Name :
$this->session->unset_userdata('key');
If you want to remove more values from session or to remove an entire array you can use the below version of unset_userdata() function.
$this->session->unset_userdata($array_items);
$this->session->unset_userdata('name');
OR
$this->session->unset_userdata(['name', 'email']);
OR
unset($_SESSION['some_name']);
// or multiple values:
unset(
$_SESSION['some_name'],
$_SESSION['another_name']
);
function logout()
{
$this->session->sess_destroy();
//$this->session->unset_userdata('username');
redirect('user');
}
This method also accepts an array of item keys to unset:
$array_items = array('username', 'email');
$this->session->unset_userdata($array_items);
Check session exist or not
if ($this->session->has_userdata('name')) {
print $this->session->has_userdata('name');
}
If you want to verify that a session value exists, simply check with isset():
// returns FALSE if the 'some_name' item doesn't exist or is NULL,
// TRUE otherwise:
isset($_SESSION['key'])
OR
$loggedIn = $this->session->userdata('username');
if($loggedIn == TRUE){
$this->load->view('dashboard');
}
else
{
redirect('Home');
}
OR
$sess_id = $this->session->userdata('username');
if(!empty($sess_id))
{
$this->load->view('dashboard');
//redirect(site_url().'/reports');
}else{
$this->session->set_userdata(array('msg'=>''));
//load the login page
//$this->load->view('login/index');
redirect('Home');
}
Set Session Time
$config['sess_expiration'] = 'somevalue'; // here value in second
$config['sess_expiration'] = 0, if you want it to never expire.
$config['timeout_duration'] = 1800; // here value in second. (30 Minutes)
$sess_expiration = 7200; // Default Session Time 2 hours
Example :- Session_controller.php
<?php
class Session_controller extends CI_Controller {
public function index() {
//loading session library
$this->load->library('session');
//adding data to session
$this->session->set_userdata('name','Sana');
$this->load->view('session_view');
}
public function unset_session_data() {
//loading session library
$this->load->library('session');
//removing session data
$this->session->unset_userdata('name');
$this->load->view('session_view');
}
}
?>
session_view.php
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter Session Example</title>
</head>
<body>
Welcome <?php echo $this->session->userdata('name'); ?>
<br>
<a href = 'http://localhost:85/CodeIgniter-3.0.1/CodeIgniter3.0.1/index.php/sessionex/unset'>
Click Here</a> to unset session data.
</body>
</html>
Example :-
Following are some syntax that are mainly used for session data:-
To retrieve session data:
$this->session->userdata('item'); // Where item is the array index like session id
To add custom session data:
$this->session->set_userdata($array); // $array is an associative array of your new data
To retrieve all session data:
$this->session->all_userdata() // Read all session values
To remove all session data:
$this->session->unset_userdata('some_name'); // Removing values from session
Controller : session_tutorial.php
<?php
Class Session_Tutorial extends CI_Controller {
public function __construct() {
parent::__construct();
// Load form helper library
$this->load->helper('form');
// Load session library
$this->load->library('session');
// Load validation library
$this->load->library('form_validation');
}
// Show session demo page
public function session_demo_page_show() {
$this->load->view('session_view');
}
// Set values in session
public function set_session_value() {
// Check input validation
$this->form_validation->set_rules('session_value', 'Session Value', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('session_view');
} else {
// Create session array
$sess_array = array(
'set_value' => $this->input->post('session_value')
);
// Add user value in session
$this->session->set_userdata('session_data', $sess_array);
$data['message_display'] = 'Value Successfully Set in Session';
$this->load->view('session_view', $data);
}
}
// Read session values
public function read_session_value() {
// Read all session values
$set_data = $this->session->all_userdata();
if (isset($set_data['session_data']) && $set_data['session_data']['set_value'] != NULL) {
$data['read_set_value'] = 'Set Value : ' . $set_data['session_data']['set_value'];
} else {
$data['read_set_value'] = 'Please Set Session Value First !';
}
$this->load->view('session_view', $data);
}
// Unset set values from session
public function unset_session_value() {
$sess_array = array(
'set_value' => ''
);
// Removing values from session
$this->session->unset_userdata('session_data', $sess_array);
$data['message_display'] = 'Successfully Unset Session Set Value';
$this->load->view('session_view', $data);
}
}
?>
views : session_view.php
<html>
<head>
<title>Session View Page</title>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css">
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
</head>
<body>
<div id="main">
<div id="note"><span><b>Note : </b></span> In this DEMO we gives you functionality to set your own session value. </div>
<div class="message">
<?php
if (isset($read_set_value)) {
echo $read_set_value;
}
if (isset($message_display)) {
echo $message_display;
}
?>
</div>
<div id="show_form">
<h2>CodeIgniter Session Demo</h2>
<?php echo form_open('session_tutorial/set_session_value'); ?>
<div class='error_msg'>
<?php echo validation_errors(); ?>
</div>
<?php echo form_label('Enter a session value :');?>
<input type="text" name="session_value" />
<input type="submit" value="Set Session Value" id='set_button'/>
<?php echo form_close(); ?>
<?php echo form_open('session_tutorial/read_session_value'); ?>
<input type="submit" value="Read Session Value" id="read_button" />
<?php echo form_close(); ?>
<?php echo form_open('session_tutorial/unset_session_value'); ?>
<input type="submit" value="Unset Session Value" id="unset_button" />
<?php echo form_close(); ?>
</div>
</div>
</body>
</html>
CSS : style.css
#main{
width:960px;
margin:50px auto;
font-family:raleway;
}
span{
color:red;
}
#note{
position:absolute;
left: 246px;
top: 81px;
}
h2{
background-color: #FEFFED;
text-align:center;
border-radius: 10px 10px 0 0;
margin: -10px -40px;
padding: 30px;
}
#show_form{
width:300px;
float: left;
border-radius: 10px;
font-family:raleway;
border: 2px solid #ccc;
padding: 10px 40px 25px;
margin-top: 70px;
}
input[type=text]{
width:100%;
padding: 10px;
margin-top: 8px;
border: 1px solid #ccc;
padding-left: 5px;
font-size: 16px;
font-family:raleway;
background-color: #FEFFED;
}
input[type=submit]{
width: 100%;
background-color:#FFBC00;
color: white;
border: 2px solid #FFCB00;
padding: 10px;
font-size:20px;
cursor:pointer;
border-radius: 5px;
margin-bottom: 15px;
}
.message{
position: absolute;
font-weight: bold;
font-size: 28px;
top:150px;
left: 862px;
width: 500px;
text-align: center;
}
.error_msg{
color:red;
font-size: 16px;
}
How to print all session variables currently set in codeigniter.
echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>';
show all session variable currently set.
print_r($_SESSION);
How to get Session Id
echo ses_id = session_id();