select and where condition in codeigniter - php

In this coding iam checking the whether email id is present in database.After that i need to change password.
function user_password($input, $serviceName){
$ipJson = json_encode($input);
$updateArray = array(
'email' => $input['email'],
'password' => md5($input['password']),
'user_modified_date' => date('Y-m-d H:i:s'),
);
$this->db->where('email', $input['email']);
$update = $this->db->update('users', $updateArray);
if ($update) {
$data['message'] = 'email id is present';
$status = $this->clamo_lib->return_status('success', $serviceName, $data, $ipJson);
}
else {
$data['message'] = 'Error In Updating Please Check Your Email ID';
$status = $this->clamo_lib->return_status('error', $serviceName, $data, $ipJson);
}
return $status;
}
if email is present in db i need to get "email id is present" message else i need to get "error"message.how i need to check the condition.

As you need to check that email address already in use or not.
So in model
$this->db->where("email",$input['email']);
$query = $this->db->get("users");
if($query->num_rows()>0){
$status['message'] = 'Email Already Exist';
}

function user_password($input, $serviceName)
{
$ipJson = json_encode($input);
$updateArray = array(
'email' => $input['email'],
'password' => md5($input['password']),
'user_modified_date' => date('Y-m-d H:i:s'),
);
$this->db->where('email', $input['email']);
$update = $this->db->update('users', $updateArray);
if ($update==TRUE)
{
$data['message'] = 'email id is present';
$status = $this->clamo_lib->return_status('success', $serviceName, $data, $ipJson);
}
else
{
$data['message'] = 'Error In Updating Please Check Your Email ID';
$status = $this->clamo_lib->return_status('error', $serviceName, $data, $ipJson);
}
return $status;
}
//change your update function in model something like this:
function update('users',$updatearray)
{
if(is_array($dataarray))
{
$this->db->trans_start();
$this->db->where('email',$this->input->post('email'));
$this->db->update('table',$updatearray);
$this->db->trans_complete();
return TRUE;
}
else
{
return FALSE
}
}

Related

login api with email, password or mobile number,password in codeigniter

I am trying to create an api which enables login for email id and password or mobile number and password in codeigniter but i was unable to do both i don't know the error. Here is my code of controller
Controller code
public function signin()
{
$this->default_file();
$responseData = array();
if(!empty($_POST['username']))
{
$userData = array();
$get_number = $this->validate_mobile($_POST['username']);
if(!empty($get_number))
{
$userData['usermob'] = $_POST['username'];
}
else
{
$userData['useremail'] = $_POST['username'];
}
$userData['userpass'] = $_POST['userpass'];
$userSignIn = $this->apm->signin($userData);
if((((!empty($userSignIn['id'])) && (!empty($userSignIn['useremail']))) ||((!empty($userSignIn['id'])) && (!empty($userSignIn['usermob'])))))
{
$session_data = array('id'=> $userSignIn['id'], 'logged_in'=> true);
$this->session->set_userdata('userLoggedIn', $session_data);
$userDetails = array();
$userDetails['id'] = $userSignIn['id'];
$getUserDetails = $this->apm->getUserDetails($userDetails);
$responseData['id'] = $getUserDetails['result']['u_id'];
$responseData['username'] = $getUserDetails['result']['username'];
$responseData['useremail'] = $getUserDetails['result']['useremail'];
$responseData['usermob'] = $getUserDetails['result']['usermob'];
$responseData['userlocation'] = $getUserDetails['result']['userlocation'];
$responseData['device_token'] = $getUserDetails['result']['device_token'];
$responseData['device_name'] = $getUserDetails['result']['device_name'];
$responseArray = array(
'apiName' => 'signin',
'version' => '1.0.0',
'responseCode' => 200,
'responseMessage' => 'logged in successfully',
'responseData' => $responseData
);
}
else
{
$responseArray = array(
'apiName' => 'signin',
'version' => '1.0.0',
'responseCode' => 204,
'responseMessage' => "Email or Passwor is incorrect.",
'responseData' => null//$responseData
);
}
}
else
{
$responseArray = array(
'apiName' => 'signin',
'version' => '1.0.0',
'responseCode' => 204,
'responseMessage' => "Sorry, please provide your input details.",
'responseData' => null//$responseData
);
}
echo json_encode($responseArray);
die();
}
My modal Code is here
public function signin($userData)
{
$arrData = array();
if(!empty($userData['useremail']) || !empty($userData['usermob']))
{
if(!empty($userData['useremail']))
{
$where = "useremail='".$userData['useremail']."'";
}
if(!empty($userData['usermob']))
{
$where = "usermob='".$userData['usermob']."'";
}
$this->db->select('*');
$this->db->from('users');
$this->db->where($where);
$result = $this->db->get()->result_array();
if(!empty($result))
{
if(!empty($userData['useremail']))
{
if(($userData['useremail']) && ($userData['userpass']))
{
$where = "useremail='".$userData['useremail']."' AND userpass='".$userData['userpass']."'";
$this->db->select('*');
$this->db->from('users');
$this->db->where($where);
$res = $this->db->get()->result_array();
if(!empty($res))
{
$arrData['id'] = $res[0]['u_id'];
$arrData['useremail'] = $res[0]['useremail'];
}
else
{
$arrData['errorLogin'] = 'Incorrect email or password';
}
}
}
if(!empty($userData['usermob']))
{
if(($userData['usermob']) && ($userData['userpass']))
{
$where = "usermob='".$userData['usermob']."' AND userpass='".$userData['userpass']."'";
$this->db->select('*');
$this->db->from('users');
$this->db->where($where);
$res = $this->db->get()->result_array();
if(!empty($res))
{
$arrData['id'] = $res[0]['u_id'];
$arrData['usermob'] = $res[0]['usermob'];
}
else
{
$arrData['errorLogin'] = 'Incorrect email or password';
}
}
}
}
else
{
$arrData['error'] = 'Please Enter username and password';
}
}
return $arrData;
}
I was trying to login with email and mobile number but my code gives only one access either with email or with mobile. i want help so that i can login with email and mobile number both.
I have tested this code using Postman, hope it can help:
public function signin($userData)
{
//get the data using useremail and userpass
$this->db->where('useremail', $userData['useremail']);
$this->db->where('userpass', $userData['userpass']);
$result = $this->db->get('users')->result_array();
//if there's no result, get the data using usermob and userpass
if (!$result) {
$this->db->where('usermob', $userData['usermob']);
$this->db->where('userpass', $userData['userpass']);
$result = $this->db->get('users')->result_array();
}
//if there's still no result, the username or password was incorect
if (!$result) {
$result = 'Wrong Username or Password';
}
return $result;
}

sending token to email in codeigniter

I'm working on a small application that can provide registering an account and sending token to complete registration to email.
I have everything working except sending emails with which I can't handle and I'm not sure how to do this. I'd really appreciat any help and explanations on how can I actually send an email instead of just displaying token in view.
There are 2 functions in which I want to send token via mail: register and forgot.
This is my Controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Main extends CI_Controller {
public $status;
public $roles;
function __construct(){
parent::__construct();
$this->load->model('User_model', 'user_model', TRUE);
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->status = $this->config->item('status');
$this->roles = $this->config->item('roles');
}
public function index()
{
if(empty($this->session->userdata['email'])){
redirect(site_url().'/main/login/');
}
/*front page*/
$data = $this->session->userdata();
$this->load->view('header');
$this->load->view('index', $data);
$this->load->view('footer');
}
public function ankieta()
{
$data = $this->session->userdata();
$this->load->view('ankieta/header');
$this->load->view('ankieta/ankieta', $data);
$this->load->view('ankieta/footer');
}
public function register()
{
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.gmail.com',
'smtp_port' => 465,
'smtp_user' => 'mymail#gmail.com',
'smtp_pass' => 'pass',
'mailtype' => 'html',
'charset' => 'utf-8'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->form_validation->set_rules('firstname', 'Imię', 'required');
$this->form_validation->set_rules('lastname', 'Nazwisko', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if ($this->form_validation->run() == FALSE) {
$this->load->view('header');
$this->load->view('register');
$this->load->view('footer');
}else{
if($this->user_model->isDuplicate($this->input->post('email'))){
$this->session->set_flashdata('flash_message', 'Podany adres email już istnieje');
redirect(site_url().'/main/login');
}else{
$clean = $this->security->xss_clean($this->input->post(NULL, TRUE));
$id = $this->user_model->insertUser($clean);
$token = $this->user_model->insertToken($id);
$qstring = base64_encode($token);
$url = site_url() . '/main/complete/token/' . $qstring;
$link = '' . $url . '';
$message = '';
$message .= '<strong>Dziekujemy za dokonanie rejestracji.</strong><br>';
$message .= '<strong>Aby dokończyć rejestrację przejdź na podany adres:</strong> ' . $link;
$to = $email;
$this->email->clear();
$this->email->from('whatever#c.com');
$this->email->to($to);
$this->email->subject('Thanks for registering');
$this->email->message($message);
if($this->email->send() === TRUE){
$this->session->set_flashdata('flash_message', 'Password reset done.');
redirect(site_url().'/main/login');
}else{
$this->session->set_flashdata('flash_message', 'Password reset fail.');
redirect(site_url().'/main/forgot');
}
};
}
}
protected function _islocal(){
return strpos($_SERVER['HTTP_HOST'], 'local');
}
public function complete()
{
$token = base64_decode($this->uri->segment(4));
$cleanToken = $this->security->xss_clean($token);
$user_info = $this->user_model->isTokenValid($cleanToken); //either false or array();
if(!$user_info){
$this->session->set_flashdata('flash_message', 'Token jest nieprawidłowy lub wygasł');
redirect(site_url().'/main/login');
}
$data = array(
'firstName'=> $user_info->first_name,
'lastName'=> $user_info->last_name,
'email'=>$user_info->email,
'user_id'=>$user_info->id,
'token'=>base64_encode($token)
);
$this->form_validation->set_rules('password', 'Hasło', 'required|min_length[5]');
$this->form_validation->set_rules('passconf', 'Potwierdź hasło', 'required|matches[password]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('header');
$this->load->view('complete', $data);
$this->load->view('footer');
}else{
$this->load->library('password');
$post = $this->input->post(NULL, TRUE);
$cleanPost = $this->security->xss_clean($post);
$hashed = $this->password->create_hash($cleanPost['password']);
$cleanPost['password'] = $hashed;
unset($cleanPost['passconf']);
$userInfo = $this->user_model->updateUserInfo($cleanPost);
if(!$userInfo){
$this->session->set_flashdata('flash_message', 'Wystąpił problem ze zmianąTwoich danych');
redirect(site_url().'/main/login');
}
unset($userInfo->password);
foreach($userInfo as $key=>$val){
$this->session->set_userdata($key, $val);
}
redirect(site_url().'/main/index');
}
}
public function login()
{
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'Hasło', 'required');
if($this->form_validation->run() == FALSE) {
$this->load->view('header');
$this->load->view('login');
$this->load->view('footer');
}else{
$post = $this->input->post();
$clean = $this->security->xss_clean($post);
$userInfo = $this->user_model->checkLogin($clean);
if(!$userInfo){
$this->session->set_flashdata('flash_message', 'Logowanie nie powiodło się');
redirect(site_url().'/main/login');
}
foreach($userInfo as $key=>$val){
$this->session->set_userdata($key, $val);
}
redirect(site_url().'/main/index');
}
}
public function logout()
{
$this->session->sess_destroy();
redirect(site_url().'/main/login/');
}
public function forgot()
{
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if($this->form_validation->run() == FALSE) {
$this->load->view('header');
$this->load->view('forgot');
$this->load->view('footer');
}else{
$email = $this->input->post('email');
$clean = $this->security->xss_clean($email);
$userInfo = $this->user_model->getUserInfoByEmail($clean);
if(!$userInfo){
$this->session->set_flashdata('flash_message', 'Adres email nie istnieje');
redirect(site_url().'/main/login');
}
if($userInfo->status != $this->status[1]){ //if status is not approved
$this->session->set_flashdata('flash_message', 'Twoje konto nie zostało aktywowane');
redirect(site_url().'/main/login');
}
//build token
$token = $this->user_model->insertToken($userInfo->id);
$qstring = base64_encode($token);
$url = site_url() . '/main/reset_password/token/' . $qstring;
$link = '' . $url . '';
$message = '';
$message .= '<strong>Zmiana hasła</strong><br>';
$message .= '<strong>Aby dokonać zmiany hasła przejdź na podany adres:</strong> ' . $link;
echo $message;
exit;
}
}
public function reset_password()
{
$token = base64_decode($this->uri->segment(4));
$cleanToken = $this->security->xss_clean($token);
$user_info = $this->user_model->isTokenValid($cleanToken); //either false or array();
if(!$user_info){
$this->session->set_flashdata('flash_message', 'Token jest nieprawidłowy lub wygasł');
redirect(site_url().'/main/login');
}
$data = array(
'firstName'=> $user_info->first_name,
'lastName'=> $user_info->last_name,
'email'=>$user_info->email,
'user_id'=>$user_info->id,
'token'=>base64_encode($token)
);
$this->form_validation->set_rules('password', 'Hasło', 'required|min_length[5]');
$this->form_validation->set_rules('passconf', 'Potwierdź hasło', 'required|matches[password]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('header');
$this->load->view('reset_password', $data);
$this->load->view('footer');
}else{
$this->load->library('password');
$post = $this->input->post(NULL, TRUE);
$cleanPost = $this->security->xss_clean($post);
$hashed = $this->password->create_hash($cleanPost['password']);
$cleanPost['password'] = $hashed;
unset($cleanPost['passconf']);
if(!$this->user_model->updatePassword($cleanPost)){
$this->session->set_flashdata('flash_message', 'Wystąpił błąd przy próbie zmiany hasła');
}else{
$this->session->set_flashdata('flash_message', 'Twoje hasło zostało zmienione. Możesz się zalogować');
}
redirect(site_url().'/main/login');
}
}
}
This is my model:
<?php
class User_model extends CI_Model {
public $status;
public $roles;
function __construct(){
// Call the Model constructor
parent::__construct();
$this->status = $this->config->item('status');
$this->roles = $this->config->item('roles');
}
public function insertUser($d)
{
$string = array(
'first_name'=>$d['firstname'],
'last_name'=>$d['lastname'],
'email'=>$d['email'],
'role'=>$this->roles[0],
'status'=>$this->status[0]
);
$q = $this->db->insert_string('users',$string);
$this->db->query($q);
return $this->db->insert_id();
}
public function isDuplicate($email)
{
$this->db->get_where('users', array('email' => $email), 1);
return $this->db->affected_rows() > 0 ? TRUE : FALSE;
}
public function insertToken($user_id)
{
$token = substr(sha1(rand()), 0, 30);
$date = date('Y-m-d');
$string = array(
'token'=> $token,
'user_id'=>$user_id,
'created'=>$date
);
$query = $this->db->insert_string('tokens',$string);
$this->db->query($query);
return $token;
}
public function isTokenValid($token)
{
$q = $this->db->get_where('tokens', array('token' => $token), 1);
if($this->db->affected_rows() > 0){
$row = $q->row();
$created = $row->created;
$createdTS = strtotime($created);
$today = date('Y-m-d');
$todayTS = strtotime($today);
if($createdTS != $todayTS){
return false;
}
$user_info = $this->getUserInfo($row->user_id);
return $user_info;
}else{
return false;
}
}
public function getUserInfo($id)
{
$q = $this->db->get_where('users', array('id' => $id), 1);
if($this->db->affected_rows() > 0){
$row = $q->row();
return $row;
}else{
error_log('no user found getUserInfo('.$id.')');
return false;
}
}
public function updateUserInfo($post)
{
$data = array(
'password' => $post['password'],
'last_login' => date('Y-m-d h:i:s A'),
'status' => $this->status[1]
);
$this->db->where('id', $post['user_id']);
$this->db->update('users', $data);
$success = $this->db->affected_rows();
if(!$success){
error_log('Unable to updateUserInfo('.$post['user_id'].')');
return false;
}
$user_info = $this->getUserInfo($post['user_id']);
return $user_info;
}
public function checkLogin($post)
{
$this->load->library('password');
$this->db->select('*');
$this->db->where('email', $post['email']);
$query = $this->db->get('users');
$userInfo = $query->row();
if(!$this->password->validate_password($post['password'], $userInfo->password)){
error_log('Unsuccessful login attempt('.$post['email'].')');
return false;
}
$this->updateLoginTime($userInfo->id);
unset($userInfo->password);
return $userInfo;
}
public function updateLoginTime($id)
{
$this->db->where('id', $id);
$this->db->update('users', array('last_login' => date('Y-m-d h:i:s A')));
return;
}
public function getUserInfoByEmail($email)
{
$q = $this->db->get_where('users', array('email' => $email), 1);
if($this->db->affected_rows() > 0){
$row = $q->row();
return $row;
}else{
error_log('no user found getUserInfo('.$email.')');
return false;
}
}
public function updatePassword($post)
{
$this->db->where('id', $post['user_id']);
$this->db->update('users', array('password' => $post['password']));
$success = $this->db->affected_rows();
if(!$success){
error_log('Unable to updatePassword('.$post['user_id'].')');
return false;
}
return true;
}
}
I'm passing $message variable to see if token works. Also while people are registering they have to input their email address. So I want tokens to go directly to emails they input in register form.
Thank you for help.
Configure your localhost mail settings as well
XAMPP
WAMP
Try This
$this->load->library('email');
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.gmail.com',
'smtp_port' => 465,
'smtp_user' => 'mymail#gmail.com',
'smtp_pass' => 'pass',
'mailtype' => 'html',
'charset' => 'utf-8'
);
$this->email->initialize($config);
$this->email->set_newline("\r\n");
$clean = $this->security->xss_clean($this->input->post(NULL, TRUE));
$id = $this->user_model->insertUser($clean);
$token = $this->user_model->insertToken($id);
$qstring = base64_encode($token);
$url = site_url() . '/main/complete/token/' . $qstring;
$link = 'Activation Link';
$message = '';
$message .= '<strong>Dziekujemy za dokonanie rejestracji.</strong><br>';
$message .= '<strong>Aby dokończyć rejestrację przejdź na podany adres:</strong> '. $link;
$toEmail = $this->input->post('email');
$to = $toEmail; # undefine
$this->email->clear();
$this->email->from('whatever#c.com');
$this->email->to($to);
$this->email->subject('Thanks for registering');
$this->email->message($message);
if(!$this->email->send())
{
echo "fail <br>";
echo $this->email->print_debugger();
/*$this->session->set_flashdata('flash_message', 'Password reset fail.');
redirect(site_url().'/main/register');*/
}
else
{
echo "Pass <br>";
/* $this->session->set_flashdata('flash_message', 'Password reset done.');
redirect(site_url().'/main/login');*/
}
Since I don't see you attempting to send an email anywhere, this is how you send an email using CI's built in library.
//load ci email library
public function send_registration_email()
{
$this->load->library('email');
$link = '' . $url . '';
$message = $link;
$to = 'some#email.com';
$this->email->clear();
$this->email->from('whatever#c.com');
$this->email->to($to);
$this->email->subject('Thanks for registering');
$this->email->message($message);
if($this->email->send() === TRUE){ //Sends a plain text email containing the link
//something
}else{
//something else
}
}

Hitting same controller url method manually gives error in Codeigniter

I am new to Codeigniter i am stuck into a problem, i have searched every where but i did not find solution to it,
My problem is when i hit a particular controller method through a link it works perfectly for eg.
http://localhost/MyProject/indexController/user_login_process
but when i hit that method manually after it renders first time properly, it renders view but following error is there.
Please help me to sort out my issue:
Controller:
public function user_login_process() {
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
if(isset($this->session->userdata['logged_in'])){
$this->load->view('teaching');
}else{
$this->load->view('index');
}
} else {
$username=$this->input->post('username');
$data = array('username' => $this->input->post('username'),'password' => $this->input->post('password'));
$result = $this->login_database->login($data);
if ($result == TRUE) {
$result = $this->login_database->read_user_information($username);
if ($result != false) {
$session_data = array('id'=>$result[0]->id,'username' => $result[0]->email,'password' => $result[0]->password);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->session->set_userdata('user_info', $session_data);
$user_info=$this->session->userdata('user_info');
$u_id=$user_info['id'];
$data['query']=$this->teaching_model->get_all_courses($u_id);
$this->load->view('teaching', $data);
}
}
else
{
$data = array('error_message' => 'Invalid Username or Password');
$this->load->view('index', $data);
}
}
}
Model:
<?php
Class Teaching_model extends CI_Model {
function get_all_courses($u_id)
{
$condition = "u_id =" . "'" . $u_id . "'";
$this->load->database();
$this->db->select("*");
$this->db->from("course");
$this->db->where($condition);
$query=$this->db->get();
return $query->result();
}
}
teaching View:
foreach ($query as $row)
{ ?>
$row->name;
<? } ?>
Try this. All codes are changed. check carefully.
Change your controller name to Home.php and inside Home too. Bcz your URL contain index is something feal bad
In Controller
public function user_login_process() {
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE)
{
# I dont know purpose od this. For now i juts redirct to login
redirect('login');
/* if(isset($this->session->userdata['logged_in']))
{
$this->load->view('teaching');
}
else
{
$this->load->view('index');
}*/
}
else
{
$this->load->database();
$username = $this->input->post('username');
$password = $this->input->post('password');
$result = $this->login_database->login($username,$password);
if ($result == 0) {
echo "Invalid login";
}
elseif ($result == 1) {
echo "Multiple account matched. Contact admin";
}
else{
$session_data = array(
'id' =>$result[0]['id'],
'username' => $result[0]['email'],
'password' => $result[0]['password'],
'logged_in' => TRUE
);
# only set one sesstion
$this->session->set_userdata($session_data);
$id = $result[0]['id']; # logged User ID
$data['query']=$this->teaching_model->get_all_courses($id);
}
if ($result)
{
$result = $this->login_database->read_user_information($username);
if ($result != false)
{
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->session->set_userdata('user_info', $session_data);
$user_info=$this->session->userdata('user_info');
$u_id=$user_info['id'];
$result2 = $this->teaching_model->get_all_courses($u_id);
if($result2 == 0){
echo "No Courses Found";
}
else{
$data['query'] = $result2;
$this->load->view('teaching', $data);
}
}
}
else
{
$data = array('error_message' => 'Invalid Username or Password');
$this->load->view('index', $data);
}
}
}
In Model*(login_database)*
public function login($username,$password)
{
$query = $this->db->query("SELECT * FROM table_name WHERE username = '$username' AND password= '$password' ");
$result = $query->result_array();
$count = count($result);
if (empty($count)) {
return 0;
}
elseif ($count) >1) {
return 1;
}
else{
return $result;
}
}
In Model*(Teaching_model)*
Class Teaching_model extends CI_Model {
function get_all_courses($id)
{
$query = $this->db->query("SELECT * FROM course WHERE u_id = $id");
$result = $query->result_array();
$count = count($result);
if (empty($count)) {
return 0;
}
else{
return $result;
}
}
}
if it is an issue with session, try using database for managing sessions:
config.php
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_sessions';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
For MySQL:
Create a table named 'ci_sessions' in your database, all the sessions will be managed using this table, and it will help you when you are hosting the website / application , may avoid some possible errors with the session variables and the permissions :
CREATE TABLE IF NOT EXISTS `ci_sessions` (
`id` varchar(40) NOT NULL,
`ip_address` varchar(45) NOT NULL,
`timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
`data` blob NOT NULL,
KEY `ci_sessions_timestamp` (`timestamp`)
);
**For Validating the users against their password **
public function validate_admin($username,$password)
{
// grab user input
if(isset($_POST['username']) AND $_POST['username'] !='')
{
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
}
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->having("rec_status != 'C' ");
// Run the query
$query = $this->db->get('employee');
// Let's check if there are any results
if($query->num_rows() == 1)
{
// If there is a user, then create session data
$row = $query->row();
$data = array(
'id_admin' => $row->id,
'first_name' => $row->first_name,
'last_name' => $row->last_name,
'email_admin' => $row->email,
'phone_admin' => $row->phone,
'acc_status_admin' => $row->rec_status,
'acc_type_admin' => $row->emp_role,
'validated_admin' => true
);
$this->session->set_userdata($data);
return true;
}
// If the previous process did not validate
// then return false.
return false;
}

Session Doesn't work in codeigniter

In my project, session is work fine before few days.But now it doesn't work. i can't find the error. plsease help me. it displays error called Severity: Notice
Message: Undefined index: firstname
Filename: user_include/header.php
Line Number: 5
A PHP Error was encountered
Severity: Notice
Message: Undefined
index: id
Filename: user_include/header.php
Line Number: 7
controller
/ Check for user login process
public function user_login_process() {
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
if(isset($this->session->userdata['logged_in'])){
//$this->load->view('admin_page');
$this->home();
}else{
$this->load->view('user_site/login_form');
}
} else {
$data = array(
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
);
$result = $this->login_database->login($data);
if ($result == TRUE) {
$email = $this->input->post('email');
$result = $this->login_database->read_user_information($email);
if ($result != false) {
$session_data = array(
'firstname' => $result[0]->firstname,
'email' => $result[0]->email,
'id' => $result[0]->id,
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->load->view("user_include/header");
$this->load->view('user_site/index');
}
} else {
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('user_site/login_form', $data);
}
}
}
// Logout
public function logout() {
// Removing session data
$sess_array = array(
'email' => ''
);
$this->session->unset_userdata('logged_in', $sess_array);
$data['message_display'] = 'Successfully Logout';
$this->load->view('user_site/login_form', $data);
}
}
?>
model
// Read data using username and password
public function login($data) {
$condition = "email =" . "'" . $data['email'] . "' AND " . "password =" . "'" . $data['password'] . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
// Read data from database to show data in admin page
public function read_user_information($email) {
$condition = "email =" . "'" . $email . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
}
?>
view
<?php
if (isset($this->session->userdata['logged_in'])) {
$firstname = ($this->session->userdata['logged_in']['firstname']);
$email = ($this->session->userdata['logged_in']['email']);
$id = ($this->session->userdata['logged_in']['id']);
} else {
header("location: login");
}
the error is in you user_include/header.php , check the id and firstname are set before you echo them out.
In your model replace following code by given code:
public function read_user_information($email) {
$condition = "email =" . "'" . $email . "'";
$this->db->select('*');
$this->db->from('user');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
To
public function read_user_information($email) {
$this->db->select('firstname, email, id');
$this->db->from('user');
$this->db->where('email',$email);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->row_array();
} else {
return false;
}
}
In your controller replace following code by given
$email = $this->input->post('email');
$result = $this->login_database->read_user_information($email);
if ($result != false) {
$session_data = array(
'firstname' => $result[0]->firstname,
'email' => $result[0]->email,
'id' => $result[0]->id,
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->load->view("user_include/header");
$this->load->view('user_site/index');
}
To
$email = $this->input->post('email');
$user_details = $this->login_database->read_user_information($email);
if ($user_details != false) {
// Add user data in session
$this->session->set_userdata('logged_in', $user_details);
$this->load->view("user_include/header");
$this->load->view('user_site/index');
}
In view, replace your code by following:
<?php
$user_details = $this->session->userdata['logged_in']);
if ($user_details != "") {
$firstname = $user_details['firstname'];
$email = $user_details['email'];
$id = $user_details['id'];
} else {
header("location: login");
}

how to update values in codeigniter rest for web service

hi all am using the following code
function update_profile_post() {
$serviceName = 'update_profile';
//getting posted values
$ip['user_id'] = trim($this->input->post('user_id'));
$ip['firstname'] = trim($this->input->post('firstname'));
$ip['lastname'] = trim($this->input->post('lastname'));
$ip['city'] = trim($this->input->post('city'));
$ip['state'] = trim($this->input->post('state'));
$ip['address'] = trim($this->input->post('address'));
$ip['phone_number'] = trim($this->input->post('phone_number'));
$ip['is_pic_changed'] = trim($this->input->post('is_pic_changed'));
$ipJson = json_encode($ip);
//validation
$ip_array[] = array("user_id", $ip['user_id'], "not_null", "user_id", "User ID is empty.");
$ip_array[] = array("firstname", $ip['firstname'], "not_null", "Firstname", "Firstname is empty.");
$ip_array[] = array("lastname", $ip['lastname'], "not_null", "lastname", "Lastname is empty.");
$ip_array[] = array("city", $ip['city'], "not_null", "city", "City is empty.");
$ip_array[] = array("state", $ip['state'], "not_null", "state", "State is empty.");
$validation_array = $this->validator->validate($ip_array);
print_r ($validation_array);
if ($validation_array !=1) {
$data['message'] = $validation_array;
$retVals = $this->clamo_lib->return_status('error', $serviceName, $data, $ipJson);
}
if ($ip['is_pic_changed'] == '1') {
$this->load->library('uploader');
$uploadPhoto = $this->uploader->upload_image($_FILES['profile_pic'], $ip);
if ($uploadPhoto == 'failed') {
$data['message'] = 'Upload failed. Please try again';
$retVals = $this->clamo_lib->return_status('error', $serviceName, $data, $ipJson);
} else {
$retVals = $this->user_model->user_update_profile_pic($ip, $uploadPhoto,$serviceName);
}
}
else{
$retVals = $this->user_model->user_update_profile($ip, $serviceName);
}
header("content-type: application/json");
echo $retVals;
exit;
}
model
function user_update_profile($input, $serviceName){
$ipJson = json_encode($input);
$updateArray = array(
'user_id' => $input['user_id'],
'firstname' => $input['firstname'],
'lastname' => $input['lastname'],
'address' => $input['address'],
'city' => $input['city'],
'state' => $input['state'],
'phone_number' => $input['phone_number'],
'user_modified_date' => date('Y-m-d H:i:s'),
);
$this->db->where('user_id', $input['user_id']);
$update = $this->db->update('users', $updateArray);
if ($update) {
$data['message'] = 'User profile updated Successfully.';
$status = $this->clamo_lib->return_status('success', $serviceName, $data, $ipJson);
} else {
$data['message'] = 'Error In Updating user profile';
$status = $this->clamo_lib->return_status('error', $serviceName, $data, $ipJson);
}
return $status;
}
here the issue is it is directly giving message updated successfully but when we are checking in db it is having all values as null what was the reason for what was wrong am doing. thanks

Categories