Email Configuration in CodeIgniter

hey guys,

lets see how to configure email in codeigniter today..

1. Create a page name email.php in project/application/config/

copy this code over there..

<?php if ( ! defined(‘BASEPATH’)) exit(‘No direct script access allowed’);
$config[‘protocol’] = ‘smtp’;
$config[‘smtp_host’] = ‘smtp.company.com’;
$config[‘smtp_port’] = 25;

?>

2. Goto your controller page..just paste this below code where ever it requires to send a mail..

$this->load->library(’email’, $config);
$this->email->from(‘fromemail@company.net’, ‘Company Name/Admin’);

$this->email->to($empemail / ‘someone@example.com’);

$this->email->subject(‘Related Subject’);
$this->email->message(‘Your message ..’);

$this->email->send();

echo $this->email->print_debugger();

Thats it..very simple..right 😉

Reference Link : Click , another

Code Igniter Error: Disallowed Key Characters

1. Search for function _clean_input_keys on /system/core/Input.php

2. Modify this line

exit(‘Disallowed Key Characters.’);

to

exit(‘Disallowed Key Characters.’ .  $str);

3. Refresh page to see the characters which generate the error

4. If you need to add those characters into the exception list, just add to this line

if ( ! preg_match(“/^[a-z0-9:_\/-]+$|/i”, $str))

I add | (pipe) character on the example above

Note: In most cases you can resolve the problem just by clearing the cookies

Create Change Password functionality in codeigniter along with css framework

hey guys, lets see the change password functionality in codeigniter using css framework called twitter bootstrap 🙂

Steps:

1. Create a view in codeigniter for a form displaying old password,new & confirm password labels…

<?php

echo form_open(‘main/changepwd’);
echo validation_errors();

?>
<table class=”table table-bordered”>

<tbody>

<tr>
<td><small><?php echo “Old Password:”;?></small></td>
<td><?php echo form_password(‘opassword’);?></td>

</tr>
<tr>
<td><small><?php echo “New Password:”;?></small></td>
<td><?php echo form_password(‘npassword’);?></td>

</tr>
<tr>
<td><small><?php echo “Confirm Password:”;?></small></td>
<td><?php echo form_password(‘cpassword’);?></td>

</tr>
</tbody>
</table>
&nbsp;&nbsp;<div id=”some”style=”position:relative;”><button type=”submit” class=”btn btn-primary”><i class=” icon-ok-sign icon-white”></i>&nbsp;Submit</button>

<?php

echo form_close();

?>

2. Add this code in Controller page..

public function changepwd(){
$this->load->library(‘form_validation’);
$this->form_validation->set_rules(‘opassword’,’Old Password’,’required|trim|xss_clean|callback_change’);
$this->form_validation->set_rules(‘npassword’,’New Password’,’required|trim’);
$this->form_validation->set_rules(‘cpassword’,’Confirm Password’,’required|trim|matches[npassword]’);

if($this->form_validation->run()!= true)
{
$this->load->view(‘settings’);

}
}
public function change() // we will load models here to check with database
{
$sql = $this->db->select(“*”)->from(“users”)->where(“email”,$this->session->userdata(’email’))->get();

foreach ($sql->result() as $my_info) {

$db_password = $my_info->password;
$db_id = $my_info->id;

}

if(md5($this->input->post(“opassword”)) == $db_password){

$fixed_pw = mysql_real_escape_string(md5($this->input->post(“npassword”)));
$update = $this->db->query(“Update `users` SET `password`=’$fixed_pw’ WHERE `id`=’$db_id'”)or die(mysql_error());
$this->form_validation->set_message(‘change’,'<div class=”alert alert-success”><a href=”#” class=”close” data-dismiss=”alert”>&times;</a>
<strong>Password Updated!</strong></div>’);
return false;

}else
$this->form_validation->set_message(‘change’,'<div class=”alert alert-error”><a href=”#” class=”close” data-dismiss=”alert”>&times;</a>
<strong>Wrong Old Password!</strong> </div>’);

return false;

}

In 2 steps you easily did change password functionality in code igniter na.. 😉 good luck 🙂

How to restrict pages based on user roles in codeigniter

Hey guys, after 3 days of my effort finally i did user role based pages restrictions.

Wanna interested to know how it can ?? 😉

Coooooooooooool.. I will explain the procedure now.. 🙂

Now iam going to build a application system where user enters with admin/user logins..if user enters with admin credentials he can access all pages..if not he cant access restricted page.

Steps:

1.create a db named user with id,email,password,role.

2.create a DB for sessions also..Clickhere

3.create necessary controllers,views etc. Here in my example..controller name is main and view name is performancefactors.

4. now create a model for users to get user details.

<?php

class Model_users extends CI_Model
{

public function can_log_in(){

$this->db->where(’email’,$this->input->post(’email’));
$this->db->where(‘password’,md5($this->input->post(‘password’)));
$query = $this->db->get(‘user’);
//$fields = $this->db->field_data(‘role’);
if($query->num_rows()==1){ //if it founds a user meaning if it find a valid credential

//return true;
return $query;
//return $fields;

}
else
{
return false;
// /return $query;
}

}// end of can_log_in

 ?>

5. Now create a model for roles..

<?php

class Model_role extends CI_Model {

 public function scalar($user,$role){

$this->db->where(’email’,$this->input->post(’email’));
$this->db->select($role); #Because I need the value
//$this->db->field_data($role);
// $this->db->where($where); #Because I need the variable column entitled siteoverview
$query = $this->db->get($user); #From the settings table
$row = $query->row_array(); // get the row
return $row[‘role’]; // return the value
}
}

?>

6. Now pass this roles in session database table..follow the controller code..

public function login_validation()
{
$this->load->library(‘form_validation’);
$this->form_validation->set_rules(’email’,’Email’,’required|trim|xss_clean|callback_validate_credentials’);
$this->form_validation->set_rules(‘password’,’Password’,’required|md5|trim’);
if($this->form_validation->run()){
//$userlevel = $query->result();
$this->load->model(‘model_role’);
$data = array(
’email’=>$this->input->post(’email’),
‘is_logged_in’=> 1,
‘role’=>$this->model_role->scalar(‘user’,’role’) // passing role details to session table
);
$this->session->set_userdata($data);
redirect(‘main/members’);
}
else
{
$this->load->view(‘login’);
}
}

public function validate_credentials($query) // we will load models here to check with database
{
//$userlevel[‘records’] = $this->model_users->can_log_in($this->input->post(’email’));
$this->load->model(‘model_users’);
if($this->model_users->can_log_in()){
return true;
//print_r($query) ;
//return $fields;
}
else
{
//print_r($query) ;
$this->form_validation->set_message(‘validate_credentials’,'<div class=”alert alert-error”><a href=”#” class=”close” data-dismiss=”alert”>&times;</a>
Incorrect Username/Password</div>’);
return false;
}
}

7. Now create a condition to view a page based on user roles..either show/restrcit…

in my case iam having user-role =1 for admin and role = 0 for normal user..

controller code for a view:

public function perffactors(){
if($this->session->userdata(‘is_logged_in’)&&$this->session->userdata(‘role’,’1′)){ //if session is created then login to members page
$this->load->view(‘perffactors’);
}else
{
redirect(‘main/restricted’);
}

}

How to use ion_auth in codeigniter??

hey folks, wanna need auth to your codeigniter applications?? its very easy which can be done in few steps:

1. Download Codeigniter and ion_auth

2. Copy all respective ion_auth files to your application directory folders like Ion_auth/config/ion_auth.php to system/application/config/ion_auth.php.

3. Create a database in mysql and execute the following queries in SQL.

CREATE TABLE `users` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`group_id` mediumint(8) unsigned NOT NULL,
`ip_address` char(16) NOT NULL,
`username` varchar(15) NOT NULL,
`password` varchar(40) NOT NULL,
`salt` varchar(40) DEFAULT NULL,
`email` varchar(100) NOT NULL,
`activation_code` varchar(40) DEFAULT NULL,
`forgotten_password_code` varchar(40) DEFAULT NULL,
`remember_code` varchar(40) DEFAULT NULL,
`created_on` int(11) unsigned NOT NULL,
`last_login` int(11) unsigned DEFAULT NULL,
`active` tinyint(1) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
);
#
# Dumping data for table ‘users’
#

INSERT INTO `users` (`id`, `group_id`, `ip_address`, `username`, `password`, `salt`, `email`, `activation_code`, `forgotten_password_code`, `created_on`, `last_login`, `active`) VALUES
(‘1′,’1′,’127.0.0.1′,’administrator’,’59beecdf7fc966e2f17fd8f65a4a9aeb09d4a3d4′,’9462e8eee0′,’admin@admin.com’,”,NULL,’1268889823′,’1268889823′,’1′);

#########################################################################

DROP TABLE IF EXISTS `groups`;

#
# Table structure for table ‘groups’
#

CREATE TABLE `groups` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`description` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
);

#
# Dumping data for table ‘groups’
#

INSERT INTO `groups` (`id`, `name`, `description`) VALUES
(1,’admin’,’Administrator’),
(2,’members’,’General User’);

 

DROP TABLE IF EXISTS `users`;

#
# Table structure for table ‘users’
#

CREATE TABLE `users` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`ip_address` varbinary(16) NOT NULL,
`username` varchar(100) NOT NULL,
`password` varchar(80) NOT NULL,
`salt` varchar(40) DEFAULT NULL,
`email` varchar(100) NOT NULL,
`activation_code` varchar(40) DEFAULT NULL,
`forgotten_password_code` varchar(40) DEFAULT NULL,
`forgotten_password_time` int(11) unsigned DEFAULT NULL,
`remember_code` varchar(40) DEFAULT NULL,
`created_on` int(11) unsigned NOT NULL,
`last_login` int(11) unsigned DEFAULT NULL,
`active` tinyint(1) unsigned DEFAULT NULL,
`first_name` varchar(50) DEFAULT NULL,
`last_name` varchar(50) DEFAULT NULL,
`company` varchar(100) DEFAULT NULL,
`phone` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
);
#
# Dumping data for table ‘users’
#

INSERT INTO `users` (`id`, `ip_address`, `username`, `password`, `salt`, `email`, `activation_code`, `forgotten_password_code`, `created_on`, `last_login`, `active`, `first_name`, `last_name`, `company`, `phone`) VALUES
(‘1′,0x7f000001,’administrator’,’59beecdf7fc966e2f17fd8f65a4a9aeb09d4a3d4′,’9462e8eee0′,’admin@admin.com’,”,NULL,’1268889823′,’1268889823′,’1′, ‘Admin’,’istrator’,’ADMIN’,’0′);
DROP TABLE IF EXISTS `users_groups`;

#
# Table structure for table ‘users_groups’
#

CREATE TABLE `users_groups` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`user_id` mediumint(8) unsigned NOT NULL,
`group_id` mediumint(8) unsigned NOT NULL,
PRIMARY KEY (`id`)
);

INSERT INTO `users_groups` (`id`, `user_id`, `group_id`) VALUES
(1,1,1),
(2,1,2);
DROP TABLE IF EXISTS `login_attempts`;

#
# Table structure for table ‘login_attempts’
#

CREATE TABLE `login_attempts` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`ip_address` varbinary(16) NOT NULL,
`login` varchar(100) NOT NULL,
`time` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
);

4. Now goto applications->config->

autoload.php : $autoload[‘libraries’] = array(‘database’,’session’,’ion_auth’);

$autoload[‘helper’] = array(‘url’,’form’);

database.php: Add database name and username of database.

routes.php:  Change default controller to auth i.e.,$route[‘default_controller’] = “auth”;

config.php:  Add base_url and encryption key

Thats it now run your application with your url..

username: admin@admin.com

password: password

How to use date picker in code igniter using twitter bootstrap??

1.Download necessary files from here

2.Copy all the required files to css,less and js of your codeigniter folder..

3. Add the following lines to your php file..

<link rel=”stylesheet” type=”text/css” href=”<?php echo base_url().’css/datepicker.css’?>”/>
<link rel=”stylesheet/less” type=”text/css” href=”<?php echo base_url().’less/datepicker.less’?>” />

<script src=”<?php echo base_url().’js/bootstrap-datepicker.js’?>”></script>

4. Add this code in php file..

<div class=”input-append date” id=”datepicker” data-date=”” data-date-format=”dd-mm-yyyy” >
<input class=”span2″ size=”16″ type=”text” value=”” disabled>
<span class=”add-on”><i class=”icon-th”></i></span>
</div>

<script>
$(‘#datepicker’).datepicker();
</script>

Now execute your php file and verify the date picker is working or not?? simple.. 😉

Try this too or use HTML5 date

Codeigniter Form_Dropdown

CodeIgniter Form_Dropdown

I had a little problem using CodeIgniter’s form_dropdown the other day. Form_dropdown produces an output similar to HTML’s form select option. I was trying to retrieve data queried from a database and display the result in a form. Well, after several test and trials, I finally got the script to work. Here’s how I did it.

Form_Dropdown

The form_dropdown function typically has 3 options. The first option is the fieldname. The second option is the option data usually laid out in an array. The third is the selected data.

form_dropdown(‘name’, array(’1′=>’one’,’2′=>’two’,’3′=>’three’),1);

This produces:

<select name=’name’>
<option value=”1″ selected=”selected”>One</option>
<option value=”2″>Two</option>
<option value=”3″>Three</option>
</select>

CodeIgniter

In CodeIgniter, I have a simple script that stores bookmarks. I categorize my bookmarks using tags. When adding bookmarks, I call on the get_dropdown_tags function in Models to retrieve all the tags and display them in array that I can use with form_dropdown. Here are my CodeIgniter entries.

Controller:

$data[‘tags’] = $this->links_model->get_dropdown_tags();

Models:

function get_dropdown_tags()
{
$tags = $this->db->query(‘select distinct tag from links’);
$dropdowns = $tags->result();
foreach ($dropdowns as $dropdown)
{
$dropdownlist[$dropdown->tag] = $dropdown->tag;
}
$finaldropdown = $dropdownlist;
return $finaldropdown;
}

Views:

In views, I’m simply calling the form_dropdown function using the $tags array passed on by the controller. It’s a pretty neat way to recall data from a database and outputting them in form_dropdown.

<?=form_dropdown(‘tag’,$tags);?>

Finally, a dropdown list that works.

Reference: Clickhere