CodeIgniter Sessions userdata issues - codeigniter

Having real big problems with CodeIgniter sessions. I can't get any userdata, really unusual thing, who can help me? I don't know how to realize it, I'm not getting the session.
Here is code:
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('admin_model');
}
public function do_login($username,$password)
{
$right_login = $this->admin_model->get_username($username);
$right_password = $this->admin_model->get_password($password);
if( ! empty($right_login) && ! empty($right_password))
{
$session = array();
$session['admin_logined'] = 'yes';
$session['user_ip'] = $_SERVER['REMOTE_ADDR'];
$this->session->set_userdata($session);
redirect('admin/main');
}
else
{
redirect('admin');
}
}
public function do_logout()
{
$session = array();
$session['admin_logined'] = '';
$session['user_ip'] = '';
$this->session->unset_userdata($session);
redirect('admin');
}
public function check_admin()
{
if(($this->session->userdata('admin_logined') === "yes"))
{
return TRUE;
}
else
{
redirect('admin');
}
}
}

To get session working in codeigniter you have to loaded session library to your controller constructor .
$this->load->library('session'); for more detail Codeigniter session.

Related

How to differentiate the multiple panels with login and session?

It create the session but does not go to index2 and index3 always redirect with else and go to index method but i want to go index2 and index3 to handle other panels also.
Session is created successfully for all just comming else condition all the time.
My form data and array is also showing when i using the print_r for my code to view if the data is comming or not.
Problem is it is showing no any error just redirect with file of index method.
My Controller
class Main extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Main_Model');
$this->load->helper('url');
$this->load->library('session');
$method = $this->router->fetch_method();
$methods = array('index','index2','index3');
if(in_array($method,$methods))
{
if(!$this->session->has_userdata('signup_email'))
{
redirect(base_url('Main/login'));
}
}
}
public function index()
{
if($this->session->has_userdata('signup_email'))
{
$this->load->view('BKO/index');
}
}
public function index2()
{
if($this->session->has_userdata('signup_email'))
{
$this->load->view('Admin/index');
}
}
public function index3()
{
if($this->session->has_userdata('signup_email'))
{
$this->load->view('Owner/index');
}
}
public function login()
{
//$data['select'] = $this->Main_Model->get_select();
$this->load->view('login');
}
public function login_process()
{
//$roll = $this->input->post('select');
echo $email = $this->input->post('email');
echo $pass = $this->input->post('upass');
$query = $this->Main_Model->login_process($email,$pass);
if($query == TRUE)
{
$this->session->set_userdata('signup_email');
$session = array(
'signup_email' => $email
);
$this->session->set_userdata($session);
redirect(base_url('Main/check_login'));
}
else
{
$this->session->set_flashdata('error','Invalid Email or Password');
redirect(base_url('Main/login'));
}
}
public function check_login()
{
if($this->session->userdata() == 'admin#gmail.com')
{
echo "Welcome - <h2>".$this->session->userdata('username')."</h2>";
redirect(base_url('Main/index2'));
}
elseif($this->session->userdata() == 'owner#gmail.com')
{
echo "Welcome - <h2>".$this->session->userdata('username')."</h2>";
redirect(base_url('Main/index3'));
}
else
{
echo "Welcome - <h2>".$this->session->userdata('username')."</h2>";
redirect(base_url('Main/index'));
}
}
public function logout()
{
$this->session->sess_destroy();
redirect(base_url());
}
My Model
public function login_process($email,$pass)
{
//$this->db->select('*');
//$this->db->where('roll_id',$roll);
$this->db->where('signup_email',$email);
$this->db->where('signup_password',$pass);
$query = $this->db->get('signup');
if($query->num_rows() > 0)
{
$this->session->set_flashdata('signup_email');
return true;
}
else
{
return false;
}
}
You missed the parameter here
if($this->session->userdata() == 'admin#gmail.com')
instead it should be
if($this->session->userdata('signup_email') == 'admin#gmail.com')

Laravel : Model saved with autogenerated uuid but instance of this model have this uuid empty

I use a trait for generate uuid on my model. It's work because, in my database the uuid value is not empty. But the current instance of my model don't have the new value.
this is the trait :
trait UuidModel
{
public static function bootUuidModel()
{
static::creating(function ($model) {
// Don't let people provide their own UUIDs, we will generate a proper one.
$model->uuid = Uuid::generate(4);
return true;
});
static::saving(function ($model) {
// What's that, trying to change the UUID huh? Nope, not gonna happen.
$original_uuid = $model->getOriginal('uuid');
if ($original_uuid !== $model->uuid) {
$model->uuid = $original_uuid;
}
return true;
});
}
public function scopeUuid($query, $uuid, $first = true)
{
if (!is_string($uuid) || (preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/', $uuid) !== 1)) {
throw (new ModelNotFoundException)->setModel(get_class($this));
}
$search = $query->where('uuid', $uuid);
return $first ? $search->firstOrFail() : $search;
}
public function scopeIdOrUuId($query, $id_or_uuid, $first = true)
{
if (!is_string($id_or_uuid) && !is_numeric($id_or_uuid)) {
throw (new ModelNotFoundException)->setModel(get_class($this));
}
if (preg_match('/^([0-9]+|[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$/', $id_or_uuid) !== 1) {
throw (new ModelNotFoundException)->setModel(get_class($this));
}
$search = $query->where(function ($query) use ($id_or_uuid) {
$query->where('id', $id_or_uuid)
->orWhere('uuid', $id_or_uuid);
});
return $first ? $search->firstOrFail() : $search;
}
}
This is my model :
class Image extends BaseModel
{
use UuidModel;
protected $table = 'images';
public $incrementing = false;
public $timestamps = true;
protected $guarded = array('id', 'timestamps', 'path');
protected $visible = array('timestamps', 'uuid');
protected $hidden = array('id', 'path');
public function Item()
{
return $this->belongsTo('App\Models\Item', 'id', 'item_id');
}
}
This is my Controller :
class ImageController extends Controller
{
...
public function store(CreateImageRequest $request, $itemSlug)
{
$item = $this->getItem($itemSlug);
$image = new Image();
$image->path = "";
$image = $item->Images()->save($image);
return Response::json($image->uuid, 201);
}
...
}
And the response is always : {} but the uuid is not empty in my database.
UPDATE
This test works :
public function store(CreateImageRequest $request, $collectionSlug, $itemSlug)
{
$item = $this->getParentItem($collectionSlug, $itemSlug);
$image = new Image();
$image->path = $filePath;
$image = $item->Images()->save($image);
$newImage = Image::find($image->id);
return Response::json($newImage->uuid, 201);
}
i'm having the same problem yesterday, here's the working trait
trait UuidTrait
{
public static function bootUuidTrait(){
static::creating(function($model){
$model->incrementing = false;
$model->{$model->getKeyName()} = Uuid::generate()->string;
});
}
}
so maybe here's the answer on your problem
static::creating(function ($model) {
// Don't let people provide their own UUIDs, we will generate a proper one.
$model->uuid = Uuid::generate(4)->string;
return true;
});
i hope i would help someone :D
You are hooking onto "creating" and "saving" events, but what you should be doing is hooking onto "creating" and "updating" events.
If you check official documentation it says that "saving" event is triggered on both creating a new model and updating an existing one - so in your case it gets called when creating new model and thus leaves "uuid" value on previous one (which is nothing); and also when updating it's the same thing.
If you switch to "creating" and "updating" events then everything will work as you want it to - basically just replace "saving" with "updating" and that's it.

Check if has beign redirected from another controller

On my login controller or view I would like to be able to see if it is possible to check if page has redirected back to login and then display bootstrap error message. I also use a MY_controller function in codeigniter
I do not want to use codeigniter session flash data message. I have my own error message as showing in code.
Is it possible to check if controller has been redirect from another controller?
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends MY_Controller {
private $error = array();
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
}
public function index() {
$data['title'] = 'Administration';
$user_id = $this->session->userdata('user_id');
if (isset($user_id)) {
$this->error['warning'] = "Working";
} else {
$this->error['warning'] = "";
}
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$this->form_validation->set_rules('username', 'Username', 'required|callback_validate');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run($this) == FALSE) {
$this->load->view('template/common/login.tpl', $data);
} else {
redirect('admin/dashboard');
}
}
public function validate() {
$this->load->library('user');
if ($this->user->login() == FALSE) {
$this->form_validation->set_message('validate', 'Does not match any of our database records');
return false;
} else {
return true;
}
}
}
MY Controller
<?php
class MY_Controller extends MX_Controller {
public function __construct() {
parent::__construct();
Modules::run('admin/error/permission/check');
}
}
Update I have tried This still displays message even though have not been redirect from another page.
Thanks to #AdrienXL for some great advice. $this->load->library('user_agent'); was the best method.
if ($this->agent->referrer()) {
$this->error['warning'] = "Working";
} else {
$this->error['warning'] = "";
}
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends MY_Controller {
private $error = array();
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
}
public function index() {
$data['title'] = 'Administration';
$this->load->library('user_agent');
if ($this->agent->referrer()) {
$this->error['warning'] = "Working";
} else {
$this->error['warning'] = "";
}
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$this->form_validation->set_rules('username', 'Username', 'required|callback_validate');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run($this) == FALSE) {
$this->load->view('template/common/login.tpl', $data);
} else {
redirect('admin/dashboard');
}
}
public function validate() {
$this->load->library('user');
if ($this->user->login() == FALSE) {
$this->form_validation->set_message('validate', 'Does not match any of our database records');
return false;
} else {
return true;
}
}
}

Codeigniter load model in controller - 500 erorr

This is my controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Order extends CI_Controller {
public function index($id=-1) {
$this->load->model('order');
}
}
When i try to open the corresponding url i get Error 500. The strange thing is that i load the model the same way on another controller without a problem.
Here goes the route and the model just in case:
Route:
$route['order/(:num)'] = "order/index/$1";
Model:
<?php
class Order extends CI_Model {
var $fullname = '';
var $email = '';
var $address = '';
var $phone = '';
var $notes = '';
var $facebook = '';
//var $canvases = '';
var $admin_notes = '';
var $status = '';
var $id = '';
var $date = '';
var $price = '';
//var $emailStatus_recivedOrder = '';
//var $emailStatus_sendedOrder = '';
//var $emailStatus_askFeedback = '';
function __construct() {
// Call the Model constructor
parent::__construct();
}
function get($search_query='', $per_page=5, $skip=0) {
if($search_query != '') {
$this->db->or_where('id', $search_query);
$this->db->or_where('email', $search_query);
$this->db->or_where('fullname', $search_query);
$this->db->or_where('phone', $search_query);
}
$query = $this->db->get('entries', $per_page, $skip);
return $query->result();
}
function count_all($search_query='') {
if($search_query != '') {
$this->db->or_where('id', $search_query);
$this->db->or_where('email', $search_query);
$this->db->or_where('fullname', $search_query);
$this->db->or_where('phone', $search_query);
}
$this->db->from('entries');
return $this->db->count_all_results();
}
function get_by_id($id) {
return $this->db->get_where('entries', array('id' => $id), 1);
}
function get_active_orders_count() {
$this->db->where('status', '1');
$this->db->from('entries');
return $this->db->count_all_results();
}
function insert_entry() {
$this->fullname = $this->input->post('fullname');
$this->email = $this->input->post('email');
$this->address = $this->input->post('address');
$this->phone = $this->input->post('phone');
$this->facebook = $this->input->post('facebook');
$this->notes = $this->input->post('notes');
$this->admin_notes = $this->input->post('admin_notes');
$this->status = $this->input->post('status');
$this->date = date('Y-m-d H:i:s');
$this->db->insert('entries', $this);
}
function update_entry() {
$this->admin_notes = $this->input->post('admin_notes');
$this->db->update('entries', $this, array('id' => $this->input->post('admin_notes')));
}
}
The error is:
A Database Error Occurred
Unable to connect to your database server using the provided settings.
Filename: core/Loader.php
Line Number: 346
You can't name your controller and model the same.
give them a different name and the problem should be fixed. So something like
Controller
class Order extends CI_Controller{ ... }
Model
class Order_model extends CI_Model{ ... }
In Objected oriented programming no two class can have the same name. As of codeigniter Controllers, Models are all classes. So, it is good practice to name your controller as ABC_Controller and model as ABC_Model to avoid class name conflict.
Controller
class ABC_Controller extends CI_Controller { .. }
Model
class ABC_Model extends CI_Model { .. }

codeigniter 404_override

I have set the $routes['404_override'] = 'city/switch_site'
now in my city controller
class City extends CI_Controller {
function __construct() {
parent::__construct();
}
function switch_site( ) {
$this->load->helper('url'); // load the helper first
$city = $this->uri->segment(1);
$segment_cnt = 1;
$valid_url = '';
switch( $city ) {
case 'pune':
$segments = $this->uri->segment_array(2);
foreach($segments as $value) {
if($segment_cnt > 1) {
$valid_url .= $this->uri->slash_segment($segment_cnt);
}
$segment_cnt++;
}
$this->config->set_item('cityid',1);
$this->config->set_item('cityname','pune');
echo APPPATH.'controllers/'.$valid_url;
include_once(APPPATH.'controllers/'.$valid_url);
break;
case 'mumbai':
$segments = $this->uri->segment_array(2);
foreach($segments as $value) {
if($segment_cnt > 1) {
$valid_url .= $this->uri->slash_segment($segment_cnt);
}
$segment_cnt++;
}
$this->config->set_item('cityid',2);
$this->config->set_item('cityname','mumbai');
include_once(APPPATH.'controllers/'.$valid_url);
break;
default:
}
}
}
how do i now pass the correct url to codeigniter router
I think you are going about this all wrong. Inside your switch instead of including other controllers which will not work use the redirect() to take them where they should go.

Resources