if else statement (not properly executing) - codeigniter - php

I have a function index() in my Admin.php controller and I'm trying to execute the 'if' statement but it is executing the 'else' statement. The admin user and password that I am logging in is correct. There's something wrong in my code and could anyone here please help me. Thanks in advance. :)
Here's my code:
//Admin.php controller
<?php
class Admin extends CI_Controller
{
public function __construct()
{
parent::__construct();
if ($this->session->userdata('logged_in') !== TRUE) {
redirect('Login');
}
}
function index()
{
if ($this->session->userdata('level') === '1') {
$this->load->view('admin_view');
} else {
echo "Access Denied";
}
}
}
//Login.php controller
<?php
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('Login_model');
}
public function index()
{
$this->load->view('login_view');
}
public function auth()
{
$username = $this->input->post('user_name', TRUE);
$password = $this->input->post('user_pass', TRUE);
$result = $this->Login_model->check_user($username, $password);
if ($result->num_rows() > 0) {
$data = $result->row_array();
$name = $data['user_name'];
$level = $data['user_lvl'];
$sesdata = array(
'user_name' => $username,
'user_lvl' => $level,
'logged_in' => TRUE
);
$this->session->set_userdata($sesdata);
if ($level === '1') {
redirect('Admin');
} elseif ($level === '2') {
redirect('User');
}
} else {
echo "<script>alert('Access Denied');history.go(-1);</script>";
}
$this->load->view('login_view');
}
}

I Suggest use double equals instead triple equals
if ($this->session->userdata('level') == '1') {
$this->load->view('admin_view');
} else {
echo "Access Denied";
}
And also check if level is string or int..

Related

Login Attempts - Codeigniter - Not Working

I want to workout a function such that unsuccessful login attempts of user are capped at 3 consecutive failed login attempts, then serve them a message to that effect. It is immediately executing this line:
if ($isBlocked) {
$this->form_validation->set_message('check_user', 'Account is temporarily blocked.');
}
Somethings wrong on my code. Thanks in advance for the help.
Controller
<?php
class Account_login extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$data['title'] = 'Account Login';
$this->load->view('account_login', $data);
}
public function verify()
{
$this->form_validation->set_rules('acc_username', 'Username', 'required');
$this->form_validation->set_rules('acc_password', 'Password', 'required|callback_check_user');
if ($this->form_validation->run() === TRUE) {
echo 'Success';
} else {
$this->index();
}
}
public function check_user()
{
$username = $this->input->post('acc_username');
$password = $this->input->post('acc_password');
$this->load->model('account_login_model');
$login = $this->account_login_model->login($username, $password);
if ($login) {
return true;
} else {
if (isset($_SESSION['error_count'][$username])) {
$_SESSION['error_count'][$username] += 1;
} else {
$_SESSION['error_count'][$username] = 1;
}
$isBlocked = $this->account_login_model->isBlocked($username);
if ($isBlocked) {
$this->form_validation->set_message('check_user', 'Account is temporarily blocked.');
} else if (isset($_SESSION['error_count'][$username]) && $_SESSION['error_count'][$username] > 2) {
$this->account_login_model->block($username);
$this->form_validation->set_message('check_user', '3 consecutive failed login attempts. Account Blocked.');
} else {
$this->form_validation->set_message('check_user', 'Invalid Username/Password');
}
return false;
}
}
}
Model
<?php
class account_login_model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function login($username, $password)
{
$condition_array = array(
'acc_username' => $username,
'acc_password' => $password
);
$rs = $this->db->get_where('accounts', $condition_array);
return $rs->row_array() ?: false;
}
public function isBlocked($username)
{
$condition_array = array(
'acc_username' => $username,
'acc_isBlocked' => 1
);
$rs = $this->db->get_where('accounts', $condition_array);
$row_count = count($condition_array);
if ($row_count > 0) {
return true;
} else {
return FALSE;
}
}
public function block($username)
{
$this->load->library('email');
$email = $this->account_lookup($username, 'acc_email');
$this->email->from('<email>', 'Yahoo.com');
$this->email->to($email);
$this->email->subject('Account Blocked');
$message = $this->load->view('account_blocked', null, TRUE);
$this->email->message($message);
$this->email->send();
$this->db->where('acc_username', $username);
return $this->db->update('accounts', array('acc_isBlocked' => 1));
}
public function account_lookup($username, $return)
{
$rs = $this->db->get_where('account', array('acc_username' => $username));
$row = $rs->row();
return $row->$return;
}
}

TMessage: Call to a member function CheckUser() on null

controller
<?php
error_reporting(E_ALL ^ E_NOTICE);
class Login extends CI_Controller {
public function _construct()
{
parent::_construct();
$this->load->model('MUser');
}
public function index()
{
if ($this->session->userdata('logged') == true ) {
redirect('rental') ;
}else{
$this->load->view('login');
}
}
public function validasi()
{
$this->load->library('Form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run() == true) {
$username = $this->input->post('username');
$password = $this->input->post('password');
if($this->MUser->CheckUser ($username,$password) == true) {
$data = array('username'=>$username, 'logged'=> true);
$this->session->set_userdata($data);
redirect('rental');
}else{
$this->session->set_flashdata('pesan', 'Username atau password anda salah');
redirect('Login');
}
} else {
$this->load->view('login');
}
}
public function logout()
{
$this->session->session_destroy();
redirect('Login', 'referesh');
}
}
?>
model
<?php
error_reporting(E_ALL ^ E_NOTICE);
class MUser extends CI_Model {
public $table = "user";
public function _construct()
{
parent::_construct();
}
public function CheckUser($username, $password) {
$query = $this->db->get_where($this->table, array('username'=>$username, 'password'=>$password));
if($query->num_rows() > 0)
{
return true;
} else {
return false;
}
}
}
?>
An uncaught Exception was encountered
Type: Error
Message: Call to a member function CheckUser() on null
Filename: C:\xampp\htdocs\rental\application\controllers\Login.php
Line Number: 30
Backtrace:
File: C:\xampp\htdocs\rental\index.php
Line: 315
Function: require_once
pliss answer my question
Try this method
"This wrong ini line 30"
public function CheckUser($username, $password) {
$query = $this->db->get_where($this->table,
array('username'=>$username, 'password'=>$password));
if($query->num_rows() > 0)
{
return true;
} else {
return false;

Load other template or redirect

In my home controller I'm checking whether the user is logged in or not. See the code below:
<?php
class Home extends Controller {
private $db;
private $session;
public function __construct($db, $session) {
$this->db = $db;
$this->session = $session;
parent::__construct($db, $session);
}
public function index() {
$this->view('home/index', array('user' => $x ) );
}
public function login() {
if( $this->session->loggedIn == true ) {
$this->index();
exit();
}
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
$sessionToDb = $this->session->startSession( $_POST['user_email'], $_POST['user_password'] );
if( $sessionToDb === true ) {
$this->index();
exit();
}
else {
$data['error'] = '<p>Fout tijdens inloggen.<br />'.$x.'</p>';
}
}
$data['url'] = $_SERVER['REQUEST_URI'];
$this->view('home/login', $data);
}
public function logout() {
$this->session->endSession();
$this->login();
exit();
}
}
?>
If the user is already logged in, he should be able to see the login screen, so I added this code:
public function login() {
if( $this->session->loggedIn == true ) {
$this->index();
exit();
}
Which works... however the URL stays the same: admin/home/login/, which could be confusing.
So alternatively I could redirect the user:
public function login() {
if( $this->session->loggedIn == true ) {
header('Location: /admin/home/index/';
exit();
}
Same goes for the logout()function.
Which is the better approach?

Pass variable from one function to another

HOw do I pass $variable from comments() to someFunction()?
class Blog extends CI_Controller {
public function index()
{
echo 'Hello World!';
}
public function comments()
{
$variable = "Hello";
}
public function someFunction()
{
echo $variable;
}
}
** EDIT ** Feel free to point out any other mistakes if you wish
class Home extends CI_Controller {
private $idArray;
function __construct()
{
parent::__construct();
$this->load->model('home_model');
$this->load->library('tank_auth');
$this->load->library('form_validation');
}
public function index() {
$home_data['initial_two'] = $this->home_model->get_two_brands();
$home_data['user_id'] = $this->tank_auth->get_user_id();
$home_data['username'] = $this->tank_auth->get_username();
$this->load->view('home_view', $home_data);
}
public function get_two() {
$get_results = $this->home_model->get_two_brands();
if($get_results != false){
$html = '';
foreach($get_results as $result){
$html .= '<li>'.$result->brand.'</li>';
}
list($result1, $result2) = $get_results;
$idOne = $result1->id;
$idTwo = $result2->id;
$this->idArray = array($result1->id, $result2->id);
//var_dump($this->idArray);
$result = array('status' => 'ok', 'content' => $html);
header('Content-type: application/json');
echo json_encode($result);
exit();
}
}//public function get_two() {
function user_pick() {
$this->form_validation->set_rules('pick', 'Pick', 'required|trim|integer|xss_clean');
$this->form_validation->set_rules('notPick', 'Not Pick', 'required|trim|integer|xss_clean');
//$arr = $this->idArray;
var_dump($this->idArray); // This is NULL
$pick = $_POST['pick'];
$notPick = $_POST['notPick'];
$user_id = $this->tank_auth->get_user_id();
if ($this->form_validation->run() == FALSE)
{
$result = array('status' => 'no', 'content' => "No good!");
header('Content-type: application/json');
echo json_encode($result);
exit();
}else{//if ($this->form_validation->run() == FALSE || $do_input == NULL)
$upload = $this->home_model->user_pick($user_id, $pick, $notPick);
$result = array('status' => 'ok', 'content' => "Thank you!");
header('Content-type: application/json');
echo json_encode($result);
exit();
}//if ($this->form_validation->run() == FALSE || $do_input == NULL)
}
}//class Home extends CI_Controller { closing bracket
/* End of file home.php */
/* Location: ./application/controllers/home.php */
class Blog extends CI_Controller {
public function index()
{
echo 'Hello World!';
}
public function comments()
{
$_SESSION['variable'] = Array('k1'=>'v1','k2'=>'v2') ;
// Store the variable in session so it can be called
// in another page or ajax call
}
public function display()
{
echo $_SESSION['variable'] ;
}
}
// my index.php file
var $blog = new Blog() ;
$blog->comments() ;
//another ajax_called.php file, call in ajax on in another browser tab
var $blog = new Blog() ;
$blog->display() ;

PHP Class Constructor, Not Clear On Passing in $_GET params

I have a class like this:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
class api {
function __construct($_GET) {
if ($_GET['method'] == "add") {
$this->add();
}
else if ($_GET['method'] == "subtract") {
$this->subtract();
}
}
function add() {
return "Adding!";
}
function subtract() {
return "Subtracting!";
}
}
$api = new api($_GET);
echo $api;
?>
When I send a URL from the browser of : test.php?method=add
I’m not getting any output or error messages. What I am missing?
Your construct function is not returning anything, only your other functions. Try this.
Class api {
function __construct($_GET) {
if ($_GET['method'] == "add") {
$this->message = $this->add();
}
else if ($_GET['method'] == "subtract") {
$this->message = $this->subtract();
}
}
function add() {
return "Adding!";
}
function subtract() {
return "Subtracting!";
}
}
$api = new api($_GET);
echo $api->message;
Change your contructor to this...
function __construct() {
if(isset($_GET)){
if($_GET['method']== "add") {
$this->add();
}
else if($_GET['method'] == "subtract"){
$this->subtract();
}}
}
You don't have to pass $_GET into the construct, as its a super global and is available everywhere, all the time
Try this
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
class api {
function __construct() {
if ($_GET['method'] == "add") {
return $this->add();
}
else if ($_GET['method'] == "subtract") {
return $this->subtract();
}
}
function add() {
return "Adding!";
}
function subtract() {
return "Subtracting!";
}
}
$api = new api();
echo $api->__construct();
?>
__construct() is the class method so in order to get the returned value from this method you have to use it this way $api->__construct()

Categories