How can get user id from database to arrowchat intergration - database

In my php i have this code, to see if the user is logged in
$auth=new auth();
$username = $auth->loggedIn();
global $crt_usr;
if(!$username) { header("Location: ".$config_live_site."/login.php?loc=account_info.php"); exit(0); }
$smarty->assign("username",$username);
$usr = new users();
$user = $usr->getUser($crt_usr);
$smarty->assign("user",$user);
And i have and this intergraton for the arrowchat
function get_user_id()
{
$userid = NULL;
if (isset($_COOKIE['userid']))
{
$userid = $_COOKIE['userid'];
}
return $userid;
}
My user id field name in my database is "id"

you can set a session that have your user id and put it to the get_user_id() function
if (isset($_SESSION['userid']))
{
$userid = $_SESSION['userid'];
}

Related

Codeigniter 3.1.9 - CI_Session is filling up my database on every refresh

I have been getting back into Codeigniter as support was picked up by BCIT. I have a problem with ci_sessions and the database driver which is regenerating the encrypted session ID and storing new data in my database on every page refresh. I'm so frustrated right now! I have both secure file storage and database for both common drivers. I want to use both or either but the effect on my application is the same whether I am using a database or files. The ci_session keeps refreshing and it is not ideal for logins, registration or any account type. Please help me see what I am doing wrong? Much appreciation granted in advance.
Config:
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'users';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
Controllers:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* User Management class created by CodexWorld
*/
class Limousers extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->model('user');
}
/*
* User account information
*/
public function account(){
print_r($_SESSION);
$data = array();
print_r($this->session->userdata());
if($this->session->userdata('isUserLoggedIn')){
$data['user'] = $this->user->getRows(array('id'=>$this->session->userdata('userId')));
//load the view
$this->load->view('limousers/account', $data);
}else{
redirect('limousers/login');
exit;
}
}
/*
* User login
*/
public function login(){
print_r($_SESSION);
if($this->session->userdata('isUserLoggedIn'))
{
print_r($this->session->userdata);
redirect('limousers/account');
exit;
}
$data = array();
if($this->session->userdata('success_msg')){
$data['success_msg'] = $this->session->userdata('success_msg');
$this->session->unset_userdata('success_msg');
}
if($this->session->userdata('error_msg')){
$data['error_msg'] = $this->session->userdata('error_msg');
$this->session->unset_userdata('error_msg');
}
if($this->input->post('loginSubmit')){
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'password', 'required');
if ($this->form_validation->run() == true) {
$con['returnType'] = 'single';
$con['conditions'] = array(
'email'=>$this->input->post('email'),
'password' => md5($this->input->post('password')),
'status' => '1'
);
$checkLogin = $this->user->getRows($con);
if($checkLogin){
$this->session->set_userdata('name',$con['conditions']['email']);
$this->session->set_userdata('isUserLoggedIn',TRUE);
$this->session->set_userdata('userId',$checkLogin['id']);
redirect('limousers/account');
exit;
}else{
$data['error_msg'] = 'Wrong email or password, please try again.';
}
}
}
//load the view
$this->load->view('limousers/login', $data);
}
/*
* User registration
*/
public function registration(){
print_r($_SESSION);
$data = array();
$userData = array();
if($this->input->post('regisSubmit')){
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|callback_email_check');
$this->form_validation->set_rules('password', 'password', 'required');
$this->form_validation->set_rules('conf_password', 'confirm password', 'required|matches[password]');
$userData = array(
'name' => strip_tags($this->input->post('name')),
'email' => strip_tags($this->input->post('email')),
'password' => md5($this->input->post('password')),
'gender' => $this->input->post('gender'),
'phone' => strip_tags($this->input->post('phone'))
);
if($this->form_validation->run() == true){
$insert = $this->user->insert($userData);
if($insert){
$this->session->set_userdata('success_msg', 'Your registration was successfully. Please login to your account.');
redirect('limousers/login');
exit;
}else{
$data['error_msg'] = 'Some problems occured, please try again.';
}
}
}
$data['user'] = $userData;
//load the view
$this->load->view('limousers/registration', $data);
}
/*
* User logout
*/
public function logout(){
$this->session->unset_userdata('isUserLoggedIn');
$this->session->unset_userdata('userId');
$this->session->sess_destroy();
redirect('limousers/login');
exit;
}
/*
* Existing email check during validation
*/
public function email_check($str){
$con['returnType'] = 'count';
$con['conditions'] = array('email'=>$str);
$checkEmail = $this->user->getRows($con);
if($checkEmail > 0){
$this->form_validation->set_message('email_check', 'The given email already exists.');
return FALSE;
} else {
return TRUE;
}
}
}
Models:
<?php if ( ! defined('BASEPATH')) exit('No direct script access
allowed');
class User extends CI_Model{
function __construct() {
$this->userTbl = 'users';
}
/*
* get rows from the users table
*/
function getRows($params = array()){
$this->db->select('*');
$this->db->from($this->userTbl);
//fetch data by conditions
if(array_key_exists("conditions",$params)){
foreach ($params['conditions'] as $key => $value) {
$this->db->where($key,$value);
}
}
if(array_key_exists("id",$params)){
$this->db->where('id',$params['id']);
$query = $this->db->get();
$result = $query->row_array();
}else{
//set start and limit
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();
if(array_key_exists("returnType",$params) &&
$params['returnType'] == 'count'){
$result = $query->num_rows();
}elseif(array_key_exists("returnType",$params) &&
$params['returnType'] == 'single'){
$result = ($query->num_rows() > 0)?$query- >row_array():FALSE;
}else{
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
}
}
//return fetched data
return $result;
}
/*
* Insert user information
*/
public function insert($data = array()) {
//add created and modified data if not included
if(!array_key_exists("created", $data)){
$data['created'] = date("Y-m-d H:i:s");
}
if(!array_key_exists("modified", $data)){
$data['modified'] = date("Y-m-d H:i:s");
}
//insert user data to users table
$insert = $this->db->insert($this->userTbl, $data);
//return the status
if($insert){
return $this->db->insert_id();
}else{
return false;
}
}
}

row() return null for specific field

Im trying to save specific field from a record into a session, for my user-role. The problem here is i cannot take any other field except nama.
controller/verify_login
public function index(){
$this->load->model('verify_login_model');
$username = $this->input->post('username');
$password = $this->input->post('password');
$result = $this->verify_login_model->verify($username, $password);
if($result == $username) {
$name = $this->verify_login_model->getinfo($username);
$this->session->set_userdata('logged_in', TRUE);
$this->session->set_userdata('username', $username);
$this->session->set_userdata('name', $name);
$this->load->view('home_view');
} else {
redirect('login');
}
model/verify_login_model
function verify($username, $password){
$this->db->select('username', 'password');
$this->db->from('tb_user');
$this->db->where('username', $username);
$this->db->where('password', MD5($password));
$this->db->limit(1);
$query = $this->db->get();
if($query->num_rows()==1) {
return $username;
} else {
return false;
}
}
function getinfo($username) {
$this->db->select('nama', 'username');
$this->db->from('tb_userInfo');
$this->db->where('username', $username);
$this->db->limit(1);
$query = $this->db->get();
if($query->num_rows()==1) {
$result = $query->row();
return $result->nama;
} else {
return false;
}
}
view
<?php echo $this->session->userdata['name']?>
the var_dump($result) : object(stdClass)#22 (1) { ["nama"]=> string(4) "test" }
if i change the return $result->nama; to $result->username; i get error : Undefined property: stdClass::$username even tho im sure 200% there's username field in the table, and tried the query directly.
There's an error in your select statement, it must be
$this->db->select('nama,username');
You are separating each column, and that's not correct, all of the columns go in one string, that's why it tells you its undefined since the only column you are sending is nama and you're sending username as the second parameter for the select.
Here's a link on active record for CodeIgniter 2.2.0

Trouble saving a session to a database by using code igniter

Controller_member
function login () {
$data['content_view']='v_form_login.php';
$this->load->view ('v_template',$data);
$username = $this->input->post('username');
$password =($this->input->post('password'));
$login_status = $this->m_member->validasi ($username, $password);
if ($login_status) {
$this->session->set_userdata('ses_username', $username);
$this->session->set_userdata('ses_login_status', $login_status);
redirect ('c_member/index');
}
}
Model_member
public function validasi ($username, $password){
$sql = "SELECT * FROM member WHERE username = '$username' AND password = '$password'";
$result = $this->db->query($sql);
$ketemu = $result->num_rows;
if($ketemu>0){
return true;
}else{
return false;
}
}
Model_slide
function delete_data($id){
$delete_date=$this->input->post('delete_date');
$query=$this->db->query("UPDATE slide SET delete_date=NOW() WHERE id='$id'");
}
I want to save a session from the login user who delete_by is username from login.

update Auth session

How to update user information stored in auth session? without logout and login again.
I think this function will do it.. but is it the best-practice?
function update($field, $value){
$this->Session->write($this->Auth->sessionKey . '.' . $field, $value);
}
Yes.
You could grab the current info array, modify it, and then call $this->Auth->login($newUserData);, but this will also renew the session (no user interaction needed, though). Note: Applies to CakePHP 2.0+ only.
I've completed update function to get an array of new values. with keys (field name):
public function update($fields, $values = null) {
if (empty(parent::$_user) && !CakeSession::check(parent::$sessionKey)) {
return false;
}
if (!empty(parent::$_user)) {
$user = parent::$_user;
} else {
$user = CakeSession::read(parent::$sessionKey);
}
if (is_array($fields)) {
if (is_array($values)) {
$data = array_combine($fields, $values);
} else {
$data = $fields;
}
} else {
$data = array($fields => $values);
}
foreach ($data as $field => $value) {
if (isset($user[$field])) {
$user[$field] = $value;
}
}
return $this->login($user);
}
(thanks to tigrang for login function)

why email component dont sent activation code to gmail?

i tried to send activation code to user mail (currently gmail) from localhost.. when submit the user information saved in database but the message not sent..so why not sent ?
var $components = array('Email','Auth','Recaptcha');
// Allows a user to sign up for a new account
function register () {
if (!empty($this->data)) {
// See my previous post if this is forgien to you
if($this->data['User']['password'] == $this->Auth->password($this->data['User']['password_confirm'])){
$this->User->data = Sanitize::clean($this->data);
// Successfully created account - send activation email
if($this->Recaptcha->valid($this->params['form'])){
if ($this->User->save()) {
$this->__sendActivationEmail($this->User->getLastInsertID());
$this->Session->setFlash('activation code sent check your mail');
$this->redirect('/users/register');
}else {
$this->data['User']['password'] = null;
}
}else{
$this->data['User']['password'] = null;
$this->Session->setFlash('wrong captcha please try again');
}
}else{
$this->data['User']['password'] = null;
$this->Session->setFlash('password not match');
}
}
}
this function Send out an activation email to the user.id specified by $user_id
#param Int $user_id User to send activation email to
#return Boolean indicates success
function __sendActivationEmail($user_id) {
$user = $this->User->find(array('User.id' => $user_id), array('User.id','User.email', 'User.username'), null, false);
if ($user === false) {
debug(__METHOD__." failed to retrieve User data for user.id: {$user_id}");
return false;
}
// Set data for the "view" of the Email
$this->set('activate_url', 'http://' . env('SERVER_NAME') . '/cakenews/users/activate/' . $user['User']['id'] . '/' . $this->User->getActivationHash());
$this->set('username', $this->data['User']['username']);
$this->Email->to = $user['User']['email'];
$this->Email->subject = env('SERVER_NAME') . ' - Please confirm your email address';
$this->Email->from = 'spcialist#gmail.com';
$this->Email->template = 'user_confirm';
$this->Email->delivery = 'smtp';
$this->Email->smtpOptions = array(
'port'=>'465',
'timeout'=>'30',
'host' => 'ssl://smtp.gmail.com',
'username'=>'spcialist#gmail.com',
'password'=>1234567,
);
$this->Email->sendAs = 'text'; // you probably want to use both :)
return $this->Email->send();
}
You wrote you are on localhost, you probably can't send emails but will probably work once online.
try debugging
function __sendActivationEmail($user_id) {
$this->Email->delivery = 'debug';
....
}
Then in your layout
<?php echo $this->Session->flash('email'); ?>
And see what comes out.

Resources