I'm rather new to Codeigniter, so I may be going about this the wrong way. In the header for my template, I have a spot for displaying account information or a message to log in.
In order for it to work properly, each controller obviously need to have the same code. To avoid this, the user guide says I should be able to extend CI_Controller and it automatically includes that code. However, that's not working for me. Here's what I've got.
application/core/MY_Controller.php:
<?php
class MY_Controller extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->model('user_model');
if ( $this->user_model->validateToken ( $this->input->cookie('session_token', TRUE) ) )
{
$data['login_info'] = 'Logged in as '. $this->user_model->getUsernameAsLink($this->input->cookie('session_token', TRUE)).'<BR />
Control Panel';
}
else
{
$data['login_info'] = 'You are not logged in<BR />
Log In';
}
}
}
?>
the model it references:
<?php
class User_model extends CI_Model {
public function __construct()
{
}
public function validateToken($token)
{
// Get token from database to check against cookie
$query = $this->db->query('SELECT `login_token` FROM `Users` WHERE `login_token` = "'.$token.'"');
// Match Found?
$rowCount = $query->num_rows();
if ( $rowCount == 1 ) {
return true;
} else {
return false;
}
}
public function getUsernameAsLink ( $token )
{
// Get token from database to check against cookie
$query = $this->db->query('SELECT `username` FROM `Users` WHERE `login_token` = "'.$token.'"');
foreach( $query->result() as $row ) {
$username = $row->username;
}
$returnString = ''.ucfirst ( $username ).'';
return $returnString;
}
}
?>
I'm getting notice errors saying that the $data['login_info'] value doesn't exist. Is there anything I've left out to keep it from processing the extension to MY_Controller?
For $data to be available in your other controllers, you need to make it available. Try setting it to $this->data and using that same thing in the other controllers.
Related
My program is not working properly, i do not know what should i do :S
I got this error message:
Take a look at this:
Here is my code:
My controller file (Home):
<?php
class Home extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model("Crudmodel");
}
public function index(){
# get all data in Study table
$selectStudys = $this->Crudmodel->selectStudys();
foreach ($selectStudys as $key => $study)
{
# get UserNames
$user = $this->Crudmodel->getName($study['user_id']);
#get Subject Names
$subject = $this->Crudmodel->getSubName($study['subject_id']);
#append both NEW VALUES to same array
if(!empty($user[0]['username'])){
$data[$key]['user_id'] = $user[0]['username'];
// your main problem can be this. may be it is not getting value from query this is why we have put validation on model function and error handler condition here
}else{
$data[$key]['user_id'] = ''; // or anything as your else condition you can use as error handler
}
if(!empty($subject[0]['name'])){
$data[$key]['subject_id'] = $subject[0]['name'];
// your main problem can be this. may be it is not getting value from query this is why we have put validation on model function and error handler condition here
}else{
$data[$key]["subject_id"] = "";
// or anything you can use as error handler
}
}
$data['records'] = $selectStudys;
$this->load->view('home', $data);
}
}
?>
Crudmodel:
class Crudmodel extends CI_Model{
public function __construct(){
parent::__construct();
$this->load->database();
}
function selectStudys()
{
$query= $this->db->query("SELECT * FROM cursadas");
if($query->num_rows()>0){
$result = $query->result_array();
}else{
$result = "";
// or anything you can use as error handler
return $result;
}
}
function getName($name)
{
$query= $this->db->query("SELECT username FROM usuarios WHERE id = $name ");
if($query->num_rows()>0){
$result = $query->result_array();
}else{
$result = "";
// or anything you can use as error handler
return $result;
}
}
Dont know what to do now :(
Hope you can help me :S
The problem is in the model. You only return something inside the else. Easy fix, move the return.
You should probably return an empty array if there are no rows. Then the foreach will still have something to work with - even if it is empty. foreach will choke if given something that cannot be used in a loop - a string for instance.
function selectStudys()
{
$query= $this->db->query("SELECT * FROM cursadas");
if($query->num_rows()>0){
$result = $query->result_array();
}else{
$result = array();
}
return $result;
}
I tried redirect() and $this->load->view('target_page') but, no success for me so please help me with this:
My controller is here:
class Login_control extends CI_Controller {
public function index() {
$this->load->model('login_model');
$this->load->helper('url');
if(isset($_POST['Logusername'])|| isset($_POST['Logpassword']))
{
$user = $_POST['Logusername'];
$pass = $_POST['Logpassword'];
$data = $this->login_model->login1($user,$pass);
if($data > 0 )
{
echo '<font color="#00FF00">'. "OK".'</font>';
$this->load->view('testing',$data);
}
else
{ echo '<font color="#FF0000">'. "Login Failed ! Username or Password is Incorrect.".'</font>' ;
}
exit();
}
$this->load->view('signup_view');
}
}
Try this code. You have written echo before redirect so, it might not work.
class Login_control extends CI_Controller{
public function index()
{
$this->load->model('login_model');
$this->load->helper('url');
if(isset($_POST['Logusername'])|| isset($_POST['Logpassword']))
{
$user = $_POST['Logusername'];
$pass = $_POST['Logpassword'];
$data = $this->login_model->login1($user,$pass);
if($data > 0 )
{
redirect('testing');
}
else
{ echo '<font color="#FF0000">'. "Login Failed ! Username or Password is Incorrect.".'</font>' ;
}
exit();
}
$this->load->view('signup_view');
}
}
Try this
In Controller
class Login_control extends CI_Controller{
public function index()
{
$this->load->model('login_model');
$this->load->helper('url');
if(isset($_POST['Logusername']) && isset($_POST['Logpassword'])) # Change || to &&
{
$user = $_POST['Logusername'];
$pass = $_POST['Logpassword'];
$data = $this->login_model->login1($user,$pass);
if($data == 1){ # check is there only one user
echo '<font color="#00FF00">OK</font>';
$this->load->view('testing',$data);
}
else{
echo '<font color="#FF0000">Login Failed ! Username or Password is Incorrect.</font>' ;
}
}
$this->load->view('signup_view');
}
}
In Model
public function login1($user,$pass)
{
$query = $this->db->query("SELECT * FROM user WHERE username= '$user' AND password = '$pass' ");
$result = $query->result_array();
$count = count($result); # get count of result
return $count; # return count to controller
}
As you are developing in codeigniter better user its inbuilt method to get and post data. For authentication u can create one library which will be autoload and check for session like userid if not found then redirect user to login page . You can create one array in that library which will defines the public / authenticated pages on bases on which you prevent user from accessing authenticated pages. You can try this for Controller :
class Login_control extends CI_Controller
{
public function index()
{
$this->load->model('login_model');
$this->load->helper('url');
$Logusername = $this->input->post('Logusername', true);
$Logpassword = $this->input->post('Logpassword', true);
if (!empty($Logusername) && !empty($Logpassword)) {
$user = $Logusername;
$pass = $Logpassword;
$data = $this->login_model->authenticate($user, $pass);
if ($data == TRUE) {
/* User this flashdata to display the message after redirect */
$this->session->set_flashdata('success', 'Logged in successfully');
redirect(site_url("dashboard"));
} else {
/* User this flashdata to display the message after redirect */
$this->session->set_flashdata('success', 'Wrong Username/password');
redirect(site_url());
}
}
$this->load->view('signup_view');
}
}
For Model
public function authenticate($Logusername, $Logpassword)
{
$select_col = "iUserId";
$where = "`vUserName` =?"; //*
$where.=" AND BINARY `vPassword`=?";
$sql = "SELECT " . $select_col . " FROM user WHERE " . $where . "";
$result = $this->db->query($sql, array($Logusername, $Logpassword))->result_array();
if (is_array($result) && count($result) > 0) {
/* Create Session and store userid */
$this->session->set_userdata("iUserId", $result[0]["iUserId"]);
return TRUE;
} else {
return FALSE;
}
}
There are many ways to authenticate the user. Check for hooks in Codeigniter
I am trying login through my login page. Each time I enter a value in the fields or just press login I notice that on my browser it stops at the run method and my page is left blank.
My database has two columns with the actual title "Username" and "Password".
I can't seem to figure out what is causing this.
Here is my login_model.php file:
<?php
class Login_Model extends BaseModel {
public function __contruct(){
parent:: __construct();
}
public function run() {
$sth = $this->database->prepare("SELECT id FROM users WHERE
Username = :username AND Password = :password");
$sth->execute(array(
':username' => $_POST['username'],
':password' => $_POST['password']
));
//$data = $sth->fetchAll();
$count = $sth->rowCount();
if ($count > 0){
//login
Session::init();
Session::set('loggedIn', true);
header('location: ../controllers/dashboard');
} else {
//show error
header('location: ../login/loginIndex');
}
}
}
?>
This is what I have within my login.php file from the controller:
<?php
class Login extends BaseController {
function __construct(){
parent::__construct();
}
//this is to avoid interference with the page that I want to call
function index() {
$this->view->render('../views/login/loginIndex');
}
function run(){
$this->model->run();
}
// public function other() {
// require '../models/loginModel.php';
// $model = new loginModel();
// }
}
This is the place I am trying to end up at:
<?php
class Dashboard extends BaseController {
function __construct(){
parent::__construct();
Session::init();
// You set the variable session: LoggedIn if they pass the condition
$logged = Session::get('loggedIn');
if ($logged == false){
Session::destroy();
header('location: ../login/loginIndex');
exit;
}
}
//this is to avoid interference with the page that I want to call
function index() {
$this->view->render('../views/dashboard/adminPage');
}
}
Update:
So after adding the following code you mentioned, this is what I got:
Notice: Undefined property: Login::$model in /apps/help-i-need-a-tutor/controllers/login.php on line 19
Fatal error: Call to a member function run() on a non-object in /apps/help-i-need-a-tutor/controllers/login.php on line 19
How do I go about finding out the cause of my issue here? I've had a look at the run method in my login_model.php class and cannot seem to find where this error may be coming from.
The error message is saying that you don't have an instance of Login_Model within Login.
Try inserting private $model above your constructor within Login, and then assigning to it within your constructor with $model = new Login_Model()
I have a model which returns a username of the person that has logged into the website to a controller. I am trying to save the username into a variable which i can user to then insert back into another table, however i am having no luck saving the data. Below is my model and controller classes.
Model:
function is_loggedin()
{
$session_id = $this->session->userdata('session_id');
$res = $this->db->get_where('logins',array('session_id' => $session_id));
if ($res->num_rows() == 1) {
$row = $res->row_array();
return $row['name'];
}
else {
return false;
}
}
Part of my Controller:
public function index()
{
$loggedin = $this->authlib->is_loggedin();
if ($loggedin === false)
$this->load->view('login_view',array('errmsg' => ''));
else
{
$this->load->view('postquestion_view',array('username' => $loggedin));
$user = $loggedin['username'];
}
}
public function askquestion()
{
$qtitle = $this->input->post('title');
$qdetails = $this->input->post('details');
$qtags = $this->input->post('tags');
$qcategory = $this->input->post('category');
$quser = $user;
Error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: user
Filename: controllers/postq.php
Line Number: 47
Here the error message is very clear. The variable $user in the last line of the function -action- askquestion() snippet is not defined. Basically, you have to read more about variables scope.
In your current situation, the code of index action should be in constructor and the variable user should be an object property. i.e it should defined globally in your controller's class and then takes its value from the constructor something like the following general demo:
<?php
class Blog extends CI_Controller {
public $user = false;
public function __construct()
{
parent::__construct();
// Your own constructor code
}
public function askquestion()
{
$qtitle = $this->input->post('title');
$qdetails = $this->input->post('details');
$qtags = $this->input->post('tags');
$qcategory = $this->input->post('category');
$quser = $this->user; //NOTICE THIS LINE
}
?>
I'm basically trying a session control. If the user is logged in, it's ok to move on. But if he's not logged in, then it will show a log-in screen and then die. However, when I use die or exit in the constructor, it does not show the log-in screen; it immediately dies. The code is as following:
private $username = null;
private $mongoid = null;
private $neoid = null;
public function __construct(){
parent::__construct();
// session to global
$this->username = $this->session->userdata( 'username');
$this->mongoid = $this->session->userdata( 'mongoid');
$this->neoid = $this->session->userdata( 'neoid');
// check if user is logged in
if( $this->username == "" || empty( $this->username)){
$this->load->view( 'access/login');
die;
}
}
It shows the log-in page if die is not written there, but with die, it does not show. Why do I want to use die? Because if I don't use, it moves on the index function and I don't want it to execute index function if the user is not logged in.
What is wrong here? What should I use to stop executing?
CodeIgniter does not instantly output the view when you load it with $this->load->view();, it puts the output of the view to the output buffer instead and after everything is loaded it flushes the whole output to the user. With that said, the problem you are seeing is that it buffers the output, then it dies without flushing it.
die is really bad and should not be used outside debugging, you should better use something like a variable switch. If it's only for the controllers scope, then you can make a
private $show_everything_else = true;
In the constructor:
if( $this->username == "" || empty( $this->username)){
$this->load->view( 'access/login');
$this->show_everything_else = false;
}
In any of the controller's methods:
if($this->show_everything_else) {
// ...
}
In any case, this solution is a quick fix and there are much better possibilities how to do this, but all of them require a different approach.
You can have a method and call it in constructor:
function __construct() {
parent::__construct();
$this->_is_logged_in();
}
and the method should look like this:
function _is_logged_in() {
$is_logged_in = $this->session->userdata('is_logged_in');
if (!isset($is_logged_in) || $is_logged_in != true) {
redirect('login');
die();
}
}
And, of course, you should have controller for login, which can look like this:
<?php
class Login extends CI_Controller {
function index() {
$this->load->view('LOGIN-VIEW');
}
function validate() {
$this->load->model('login_model');
$data = $this->login_model->validate();
if ($data != false) {
$data['is_logged_in'] = true;
$this->session->set_userdata($data);
redirect('MAIN-CONTROLLER-AFTER-LOGIN');
}
else {
$this->index();
}
}
function logout() {
$this->session->sess_destroy();
$this->index();
}
}
This what i posted, also preserve sessions in database.
Login model can be as primitive as this:
class Login_model extends CI_Model {
function validate() {
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get('users');
if($query->num_rows == 1) {
$data = $query->row_array();
return $data;
} else {
return false;
}
}
The Controller class will automatically run the index() function. So, to make it work, you must return the index() if the login check in construct is failed. Here what you can do:
private $username = null;
private $mongoid = null;
private $neoid = null;
private $no_login = false;
public function __construct(){
parent::__construct();
// session to global
$this->username = $this->session->userdata( 'username');
$this->mongoid = $this->session->userdata( 'mongoid');
$this->neoid = $this->session->userdata( 'neoid');
// check if user is logged in
if( $this->username == "" || empty( $this->username)){
$this->load->view( 'access/login');
$this->no_login = true;
}
}
function index(){
if($this->no_login) return;
// another statement if login success.....
}