I am new to codeigniter and I am having some issues loading a model in my constructor method. Could someone help me out? Below is the code from the controller I am trying to load the model from...
<?php
class Login extends CI_Controller {
function Login(){
$this->load->model('membership_model');
}
public function index(){
$this->load->view('login_view.php');
}
public function authenticate(){
$user = $this->input->post('username');
$pass = sha1($this->input->post('password'));
if($user != null && $pass != null){
$access = $this->membership_model->request_access($user, $pass);
if($access == true){
$cookie = array(
'name' => 'username',
'value' => $user,
'expire' => '86500',
'domain' => 'unleashourmedia.com',
'path' => '/',
'prefix' => '',
'secure' => TRUE
);
$this->input->set_cookie($cookie);
echo "cookie";
} else {
redirect('login');
}
}
}
}
?>
The problem is you are not calling the constructor of the parent class.
Add this as the first line in your constructor:
parent::__construct();
function Login(){
$this->load->model("membership_model","",TRUE);
}
//make sure you call parent constructor before anything in that constructor like this
function Login(){
parent::__construct();
$this->load->model('membership_model');
}
//and you may also try to name the constructor __construct
function __construct(){
parent::__construct();
$this->load->model('membership_model');
}
Related
iam trying to make a simple login session , but i get redirected to login page, here is my
Login.php controller.
> <?php class Login extends CI_Controller
{ function __construct()
{
> parent::__construct();
if($this->session->userdata('admin'))
> redirect('admin/dashboard');
}
function index()
{
> $this->load->view('admin/login', $data);
} function verify() {
> //username:admin password:123456
$this->load->model('admin');
> $check = $this->admin->validate();
if($check) {
> $this->session->set_userdata('admin','1');
> redirect('admin/dashboard');
}
else
{
>
redirect('admin'); } }
>
>
>
> }
and here is my Dashboard.php controller which the ademin would redurect if the username and password are correct
<?php
class Dashboard extends CI_Controller
{
function __construct()
{
parent::__construct();
if(!$this->session->userdata('admin'))
redirect('admin');
}
function index()
{
$this->load->view('admin/dashboard');
}
function logout()
{
$this->session->sess_destroy();
redirect('admin');
}
}
and here is database.php
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'ASGB-test',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
)
;
here is my autoload.php, i activate database and session libraries here
$autoload['libraries'] = array('database','session');
here is routes.php, welcome controller is basically the original codeigniter welcome view, and i define the admin rout as well
$route['default_controller'] = 'welcome';
$route['admin'] = 'admin/login';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
here is Admin_model.php
<?php
class Admin_model extends CI_Model
{
function validate()
{
$arr['username'] = $this->input->post('Username');
$arr['password'] = md5($this->input->post('Password'));
return $this->db->get_where('admins',$arr)->row();
}
}
I am sure im entering correct password and username , but it just redirect me to the login page
you have to use
session_start();
at the very beginning of the php script of every page that needs session variables.
Solved, i actually was miss spelling the "username" and "password", by solving that i logged in successfully .thanks for your answers
First, I don't know what the $data is doing in your index() of the Login controller, and what the validate() is doing in your model admin, then I think it would be better to put the login and logout function in the Login Controller as the following:
<?php
class Login extends CI_Controller{
function __construct(){
parent::__construct();
}
function index() {
$this->load->view('admin/login');
}
public function log_in()
{
$this->load->model('admin');
$this->form_validation->set_rules('username', 'Username', 'trim|required', array('required' => 'Username required'));
$this->form_validation->set_rules('password', 'Password', 'trim|required', array('required' => 'Password required'));
//username:admin password:123456
if ($this->form_validation->run() !== false) {
$username = $this->input->post('username');
$password = $this->input->post('password');
$check = $this->admin->validate($username, $password);
if ($check != false) {
$this->session->set_userdata('admin','1');
redirect('Dashboard');
} else {
redirect('Login');
}
}
$this->load->view('admin/login');
}
public function log_out()
{
$this->session->sess_destroy();
redirect('Login');
}
}
?>
then your Dasboard Controller as follows:
<?php
class Dashboard extends CI_Controller
{
function __construct()
{
parent::__construct();
if(!$this->session->userdata('admin'))
redirect('Login');
}
function index()
{
$this->load->view('admin/dashboard');
}
}
?>
and the Admin model as follows :
<?php
class Admin extends CI_Model
{
function validate($username, $password)
{
$this->db->select('*')
->from('admins')
->where('username', $username)
->where('password', md5($password));
$query = $this->db->get();
return $query->result();
}
}
?>
I have Controller called login.php that will take login credentials, if true user will be directed to a method profile() in another controller called page.php.
In that profile() method only contain a command to load the view of user's profile.
So the route is like this:
Home->login->profie
But when I try to bypass the login process via url like this
Home->profile
The system still accept that. How can I make a rule that a user can't open profile if they're not logged in?
Here's the Controller:
page.php
class page extends CI_Controller {
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');
}
function index() {
$this->load->view('page_header');
$this->load->view('content_front');
$this->load->view('page_footer');
}
function login() {
$this->load->view('page_header');
$this->load->view('content_login');
$this->load->view('page_footer');
}
function register() {
$this->load->view('page_header');
$this->load->view('content_register');
$this->load->view('page_footer');
}
function profile(){
$this->load->view('page_header');
$this->load->view('content_profile');
$this->load->view('page_footer');
}
function success() {
$this->load->view('page_header');
$this->load->view('content_success');
$this->load->view('page_footer');
}
function logout()
{
//destroy session
$data = array('login' => '', 'uname' => '', 'uid' => '');
$this->session->unset_userdata($data);
$this->session->sess_destroy();
redirect('page/index');
}
}
?>
login.php
<?php
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url','html','security'));
$this->load->library(array('session','form_validation'));
$this->load->database();
$this->load->model('user_model');
}
function index()
{
//get form input
$username = $this->input->post('username');
$password = $this->input->post('password');
//form validation
$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)
{
//validation fail
$this->load->view('content_login');
}
else
{
//check user credentials
$uresult = $this->user_model->get_user($username, $password);
if(count($uresult)>0)
{
//set session
$sess_data = array('login' => TRUE, 'uname' => $uresult[0]->username,'uid' => $uresult[0]->id);
$this->session->set_userdata($sess_data);
$this->load->library('../controllers/page');
$this->page->profile();
}
else
{
$this->session->set_flashdata('msg','<div class = "alert alert-danger text-center">Wrong Email/Password</div>');
$this->load->library('../controllers/page');
$this->page->login();
}
}
}
}
?>
Can anyone please help me how to fix this?
Thank you.
Add a constructor to every applicable controller.
Let the constructor check if the user is logged in, possibly by checking if a particular session exists. If it doesn't redirect to the login page.
Something like below
function __construct(){
parent::__construct();
if(!$this->session->userdata('userid')){
redirect('user/login');
}
}
use this at the top of the page you don't want it accessed when not logged in (supposing you've already set session data)
<?php if (!isset($_SESSION['username'])) {
redirect(base_url());
} ?>
Before showing that page, you should check whether that session exist or not, like if($this->session->userdata('username')). If exists, show that page, if not show any warning.
You can try
if ($this->session->userdata('login') == true) {
redirect('controller');
}
Login Controller
<?php
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url','html','security'));
$this->load->library(array('session','form_validation'));
$this->load->database();
$this->load->model('user_model');
}
function index()
{
if ($this->session->userdata('login') == true) {
redirect('controller');
}
//get form input
$username = $this->input->post('username');
$password = $this->input->post('password');
//form validation
$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)
{
//validation fail
$this->load->view('content_login');
}
else
{
//check user credentials
$uresult = $this->user_model->get_user($username, $password);
if(count($uresult)>0)
{
//set session
$sess_data = array('login' => TRUE, 'uname' => $uresult[0]->username,'uid' => $uresult[0]->id);
$this->session->set_userdata($sess_data);
$this->load->library('../controllers/page');
$this->page->profile();
}
else
{
$this->session->set_flashdata('msg','<div class = "alert alert-danger text-center">Wrong Email/Password</div>');
$this->load->library('../controllers/page');
$this->page->login();
}
}
}
}
Couple things I noticed also in Codeigniter 3 + versions the first letter must only be upper case on FILENAME and Controller Class
Also you don't need to close the controllers and model with ?> https://www.codeigniter.com/user_guide/general/styleguide.html#php-closing-tag
If for example you don't want the user to enter a function without login, you could check the session in the constructor of the class.
If it's only for a specific function, you could just also check the session in the function directly.
Create a helper file login_helper.php
function check_login( $session ) {
$CI =& get_instance();
$CI->load->helper('url');
if(!$session->userdata('login')){
redirect(base_url());
}
}
Now use this helper function in controllers where login is mandatory
class page extends CI_Controller {
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');
}
function index() {
$this->load->view('page_header');
$this->load->view('content_front');
$this->load->view('page_footer');
}
function login() {
$this->load->view('page_header');
$this->load->view('content_login');
$this->load->view('page_footer');
}
function register() {
$this->load->view('page_header');
$this->load->view('content_register');
$this->load->view('page_footer');
}
function profile(){
check_login();
$this->load->view('page_header');
$this->load->view('content_profile');
$this->load->view('page_footer');
}
function success() {
$this->load->view('page_header');
$this->load->view('content_success');
$this->load->view('page_footer');
}
function logout()
{
//destroy session
$data = array('login' => '', 'uname' => '', 'uid' => '');
$this->session->unset_userdata($data);
$this->session->sess_destroy();
redirect('page/index');
}
}
?>
Note: add login_helper in autoload.php in config folder.
$autoload['helper'] = array('login','url','cookie');
if($this->session->userdata('logged_in') == FALSE) {
$this->session->set_flashdata('error','<p class="alert alert-danger">Please login to view this page.</p>');
redirect('login_c');
exit;
}
The Session library is autoloaded
My model:
class Login_model extends CI_Model{
function __construct(){
parent::__construct();
}
public function validate(){
$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);
$query = $this->db->get('users');
if($query->num_rows == 1)
{
$row = $query->row();
$data = array(
'id' => $row->id,
'first_name' => $row->first_name,
'last_name' => $row->last_name,
'username' => $row->username,
'validated' => true
);
$this->session->set_userdata($data); // ### line 28 ###
return true;
}
return false;
}
}
Gives this error:
Fatal error: Call to undefined method Session::set_userdata() in
/var/www/codeIgniterTest/_application/models/login_model.php on line
28
Have you loaded the Session library?
class Login_model extends CI_Model {
function __construct()
{
parent::__construct();
$this->load->library('session');
}
Try debugging and check all the included files by.
$included_files = get_included_files();
foreach ($included_files as $filename) {
echo "$filename\n";
}
I found the problem. I created my own Session class, but forgot to extend the CI_Session.
Thanks for the help!
I have implemented the login logic in an MVC application; I want to see if the user has filled the username and passowrd incorrectly and if so I want to show a notifictaion in the view; so I'm passing this information via $data['er']; but for some reason it is not catching this data:
Please let me know if my question is clear or not; and if any clarification is needed, please let me know which part is ambiguous
My code:
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$GLOBALS['er'] = False;
}
public function index() {
$data['er']=$GLOBALS['er'];
$data['main_content'] = 'login_form';
$this->load->view('includes/template', $data);
}
public function validate_credentials() {
$this->load->model('user_model');
$query = $this->user_model->validate();
if ($query) {
$data = array(
'username' => $this->input->post('username'),
);
$this->session->set_userdata($data);
redirect('project/members_area');
} else {
$GLOBALS['er'] = TRUE;
$this->index();
}
}
}
Don't use GLOBALS you can just use a private variable in your class.
Create the variable above your __construct function like private $er
In your __contruct function set the default value
Set and get in your public function using $this->er
Implemented in your code:
class Login extends CI_Controller {
private $er;
public function __construct() {
parent::__construct();
$this->er = FALSE;
}
public function index() {
$data['er']= $this->er;
$data['main_content'] = 'login_form';
$this->load->view('includes/template', $data);
}
public function validate_credentials() {
$this->load->model('user_model');
$query = $this->user_model->validate();
if ($query) {
$data = array(
'username' => $this->input->post('username'),
);
$this->session->set_userdata($data);
redirect('pmpBulletin/members_area');
//die(here);
} else {
$this->er = TRUE;
$this->index();
}
}
}
i tried follow from http://book.cakephp.org/2.0/en/development/sessions.html#creating-a-custom-session-handler then i cant solve this and im really confuse about this :(
become like this:
<?php
App::uses('DatabaseSession', 'Model/Datasource/Session');
class CartSession implements CakeSessionHandlerInterface {
public $cacheKey;
public function __construct() {
$this->cacheKey = Configure::read('Session.handler.cache');
parent::__construct();
}
// read data from the session.
public function read($id) {
$result = Cache::read($id, $this->cacheKey);
if ($result) {
return $result;
}
return parent::read($id);
}
// write data into the session.
public function write($id, $data) {
$result = Cache::write($id, $data, $this->cacheKey);
if ($result) {
return parent::write($id, $data);
}
return false;
}
// destroy a session.
public function destroy($id) {
$result = Cache::delete($id, $this->cacheKey);
if ($result) {
return parent::destroy($id);
}
return false;
}
// removes expired sessions.
public function gc($expires = null) {
return Cache::gc($this->cacheKey) && parent::gc($expires);
}
}
?>
Output Error:
Fatal error: Class CartSession contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (CakeSessionHandlerInterface::open, CakeSessionHandlerInterface::close) in /Users/user/Sites/app/shop/Model/Datasource/Session/CartSession.php on line 43
I did added in core.php:
Configure::write('Session', array(
'defaults' => 'database',
'handler' => array(
'engine' => 'CartSession',
'model' => 'Session',
'cache' => 'apc'
)
));
Cache::config('apc', array('Engine' => 'Apc'));
You need to extend DatabaseSession. So your class declaration will look like:
class CartSession extends DatabaseSession implements CakeSessionHandlerInterface