$_POST is null in codeigniter - php

when I'm login, the login controller will handle my login but Why my $_post in the controller is always false? (I know because is null but why is null?) and then is make me can't login to my home page. please, someone, help me
I have a controller like this
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('M_login');
}
public function index() {
//if user has log-in, redirect to somewhere
if($this->session->userdata('loggedin')) {
redirect('home');
//else go to login form
} else {
if($_POST["username"]) {
echo $this->M_login->ceklogin();
redirect('login');
} else {
//if user input the wrong email/data
$this->session->set_flashdata("msg_login", "Wrong credentials.");
redirect('home/login');
}
}
}
}
This is my view
<?php
$this->load->view('parts/header');
?>
<body>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">WoW Page</h3>
</div>
<div class="panel-body">
<form action="<?php echo base_url();?>index.php/login" method="POST">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Username" name="username" type="text" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" value="">
</div>
<?php if ($this->session->flashdata('msg_login') != '') { ?>
<div class="alert alert-danger alert-dismissible" role="alert">
<center><i class="fa fa-warning" aria-hidden="true"></i> <?php echo $this->session->flashdata('msg_login'); ?></center>
</div>
<?php } ?>
<!-- Change this to a button or input when using this as a form -->
<input type="submit" class="btn btn-lg btn-danger btn-block" value="Login">
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- jQuery -->
<script src="<?php echo base_url();?>assets/bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="<?php echo base_url();?>assets/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Metis Menu Plugin JavaScript -->
<script src="<?php echo base_url();?>assets/bower_components/metisMenu/dist/metisMenu.min.js"></script>
<!-- Custom Theme JavaScript -->
<script src="<?php echo base_url();?>assets/dist/js/sb-admin-2.js"></script>
</body>
</html>
And this is my model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class M_login extends CI_Model {
// cek login
public function ceklogin() {
$query = $this->db->get_where('admin', array(
'username'=>$this->input->post('username'),
//password converted to md5
'password'=>md5($this->input->post('password'))
));
$user = $query->row();
if(count($user) != 0) {
//setting isi session
$sesi = array(
'admin_id'=>$user->admin_id,
'username'=>$user->username,
'level'=>$user->level,
'loggedin'=>true
);
$this->session->set_userdata($sesi);
} else {
$data = array('loggedin'=>false);
}
}
}
?>
Thank You
Thank You
Thank You

There are several problems. First one is that your model does not return anything that the controller can use. Here are my thoughts on how the model should be done.
public function ceklogin($user_name, $password)
{
$user = $this->db
->select('admin_id, username, level')
->get_where('admin', array('username'=>$username, 'password'=>md5($password)))
->row_array();
if( ! empty($user))
{
$user['loggedin'] = true; //add 'loggedin' to $user array
$this->session->set_userdata($user);
return TRUE;
}
$_SESSION['loggedin'] = false;
return FALSE;
}
Notice that there are two arguments to the function - $user name and $password. These need to be provided by the controller. Notice that ceklogin() returns TRUE or FALSE depending on if a row is found in the database.
I did not change the password hashing - BUT YOU SHOULD. Use the functions that #RiggsFolly told you about in the comments. You should also look into sanitizing and validating the inputs. Never trust user input!
Notice the database call returns a row_array() results. This will be the exact data structure you wanted for session data. That means you do not have to build an array for set_userdata() because the database made it for you.
Here is the revised index() function.
public function index()
{
//if user has log-in, redirect to somewhere
if($this->session->userdata('loggedin'))
{
redirect('home');
}
// get the inputs so they can be passed to the model
$user_name = $this->input->post('username');
$password = $this->input->post('password');
// if we have inputs, check for valid username & password
if($user_name && $password)
{
if($this->M_login->ceklogin($user_name, $password))
{
// model returned true
redirect('home'); //if 'home' is where valid users go
}
}
// If not all inputs (null/empty $_POST)
// or the wrong inputs (ie. model returned false)
$this->session->set_flashdata("msg_login", "Wrong credentials.");
redirect('home/login');
}
I removed many (all) the else statements. They were not needed because all the if blocks end in a call to redirect() and that function calls exit; meaning that a call to redirect() never returns to where it was called from.
You should be using the CodeIgniter Validation Library instead of the crude construct
if($user_name && $password)
But that's better than nothing.

Related

Make Filtering for Codeigniter Login

I have a Login system in my CodeIgniter project. But, I want to make some condition filtering like this :
If username not admin then go back to login page
Here's my Model script :
//Get Data Login
public function getAllData($table)
{
return $this->db->get($table)->result();
}
function login($username, $password) {
//create query to connect user login database
$this->db->select('*');
$this->db->from('artist');
$this->db->where('username', $username);
$this->db->where('password', MD5($password));
$this->db->limit(1);
//get query and processing
$query = $this->db->get();
if($query->num_rows() == 1) {
return $query->result(); //if data is true
} else {
return false; //if data is wrong
}
}
And on every Controller I have:
function __construct(){
parent::__construct();
$this->load->model('m_admin_data');
$this->load->helper(array('url'));
//CEK LOGIN
if($this->session->userdata('login_status') != TRUE ){
$this->session->set_flashdata('notif','Login Gagal!! Username atau Password Salah !');
redirect('Admin_login');
};
$this->load->model('m_admin_data');
// END CEK LOGIN
}
Can anybody please help me do this?
only username == admin can access this page
and this for View files :
<form class="form-signin form-horizontal m-t-20" action="<?= site_url('Admin_login/cek_login')?>" method="post">
<!-- NOTIF -->
<?php
$message = $this->session->flashdata('notif');
if($message){
echo '<p class="alert alert-success text-center">'.$message .'</p>';
}?>
<div class="form-group ">
<div class="col-xs-12">
<input type="text" class="form-control" placeholder="Username" name="username" required="">
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input type="password" class="form-control" placeholder="Password" name="password" required="">
</div>
</div>
<div class="form-group text-center m-t-30">
<div class="col-xs-12">
<button class="btn btn-custom btn-bordred btn-block waves-effect waves-light" type="submit">Sign in</button>
</div>
</div>
<div class="form-group m-t-30 m-b-0">
</div>
</form>
I Think you will be better served defining those condition on hooks. Use pre_controller hooks. Then, you won't have to declare condition on each controller.
If the condition on the hooks is not met, then you just need to redirect to login page. In the pre_controller hooks, skip checking the login condition on login page.
Hooks Docs
You can create a MY_Controller.php in application/core and have your controllers where you want this logic to be applied extend MY_Controller rather than CI_Controller
Example MY_Controller:
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('auth_model', 'auth');
if (!$this->auth->is_logged()) {
redirect('login');
}
if (!$this->auth->is_admin()) {
redirect('login');
}
}
}
You should not use MY_Controller for the login controller or you will end up in an infinite redirect loop; so this is only really for protected pages. You can also call it something else and even have different core controllers using requires.
That being said I'm not sure why you are allowing login for non-admins if all you are going to do is redirect them to the login page.
Also md5() is not a secure way of hashing passwords. Even php says so.
Would you please add one more where statement in your function see below
function do_validate() {
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE)
{
# not allowed, display error message
$this->load->view('myform');
}
else
{
# success
$this->load->view('formsuccess');
if(login($username, $password)) {
# redirect page after login
} else {
# show error message
}
}
}
public function username_check($str){
if ($str != 'admin'){
$this->form_validation->set_message('username_check', 'Only admin login allowed');
return FALSE;
} else {
return TRUE;
}
}
function login($username, $password) {
//create query to connect user login database
$this->db->select('*');
$this->db->from('artist');
$this->db->where('username', $username);
$this->db->where('password', MD5($password));
$this->db->limit(1);
//get query and processing
$query = $this->db->get();
if($query->num_rows() == 1) {
return $query->result(); //if data is true
} else {
return false; //if data is wrong
}
}

Validating a form hiding controller from URL Codeigniter

I'm facing a problem when trying to create a simple login system. This is how it works and shows what my problem is.
The login page contains a simple form, and opens a form to the controller 'Verify_login'. This Verify_login controller does some basic form validations, and then queries the database to check if the user entered correct credentials. When this form is submitted, it automatically directs the user to website.com/verify_login, while I would like it to remain website.com/login. I am not able to solve this problem using the routes file, because this causes the two pages to be both redirected to the same page. Does anyone have a solution to this? I'm using the Codeigniter framework.
login.php
<div class="content-block">
<h1>Login</h1>
<div class="content-inner-block">
<?php echo validation_errors(); ?>
<?php echo form_open('Verify_login'); ?>
<div class="login wrap">
<input type="text" name="username" id="user" placeholder="Username">
<input type="password" name="password" id="pass" placeholder="**********">
<input type="submit" value="Log in">
</div>
<?php echo form_close("\n")?>
</div>
Verify_login.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Verify_login extends CI_Controller{
public function index(){
$this->load->model('User_model');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == FALSE){
$this->load->view('pages/login');
return false;
}
$result = $this->User_model->login($this->input->post('username'), $this->input->post('password'));
if($result){
echo 'loggedin';
} else {
echo 'wrong';
}
}
}
?>

Can't use Ion Auth's login method in another controller

I added controllers/Site.php , views/site/login.php to my project but when I submit login form i always get */application/views/site/login#
Do anyone knows why? whats the problem?
here is my Site.php :
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Site extends MY_Controller {
function __construct() {
parent::__construct();
$this->load->library('ion_auth');
$this->load->library('form_validation');
$this->load->helper('url');
$this->load->helper('string');
$this->load->database();
$this->form_validation->set_error_delimiters($this->config->item('error_start_delimiter', 'ion_auth'), $this->config->item('error_end_delimiter', 'ion_auth'));
$this->lang->load('auth');
$this->load->helper('language');
$this->data['pageTitle'] = $this->lang->line('login_page_title');
}
//redirect if needed, otherwise display the user list
function index() {
if (!$this->ion_auth->logged_in()) {
//redirect them to the login page
redirect('site/login', 'refresh');
} else if (!$this->ion_auth->is_admin()) { //remove this elseif if you want to enable this for non-admins
//redirect them to the home page because they must be an administrator to view this
return show_error('You must be an administrator to view this page.');
}
}
//log the user in
function login() {
$this->data['title'] = "Login";
//validate form input
$this->form_validation->set_rules('identity', 'Identity', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == true) {
//check to see if the user is logging in
//check for "remember me"
$remember = (bool) $this->input->post('remember');
if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember)) {
//if the login is successful
//redirect them back to the home page
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect('/', 'refresh');
} else {
//if the login was un-successful
//redirect them back to the login page
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect('site/login', 'refresh'); //use redirects instead of loading views for compatibility with MY_Controller libraries
}
}
$this->_render_page('site/login', $this->data);
}
}
And here is my simple login.php :
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Login</h1>
<form role="form" action="#" method="post">
<div class="input-group">
<input type="email" id="identity" name="identity" placeholder="Your email address" value="admin#mail.com">
</div>
<div class="input-group">
<input type="password" id="password" name="password" placeholder="Your password" value="password">
</div>
<div class="checkbox-group">
<input type="checkbox" value="1" id="remember" name="remember" data-toggle="checkbox">
<label for="remember">Remember Me</label>
</div>
<button type="submit">Log me in</button>
</form>
</body>
</html>
This action="#" looks very strange. I think you should change this with action='/site/login'. You don't need use base_url() as commented above. Related path should be enough.

CodeIgniter Button does not Trigger Action

I have been searching through various questions on the site with no luck. The closest I got to an answer, as far as I can tell, was through the following question: CodeIgniter's form action is not working properly.
The problem is that when I press the login button nothing happens so the action property in the HTML form is not being triggered. I have looked at my routes as well with no luck.
The HTML code is in my view folder and is the following:
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-body">
<form role="form" method="post" action="<?php echo base_url() ?>index.php/login">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Username" name="username" type="username" required>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" required>
</div>
<a type="submit" id="login-button" style="navy" class="btn btn-lg btn-success btn-block">Login</a>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
My controller is called pages.php, and it's function, login is the following:
public function login()
{
$this->load->helper('form');
$username = $this->input->post('username');
$password = $this->input->post('password');
if ($username != false && $password != false)
{
$loginDetails = $this->pages_model->retrieveLoginDetails($username, $password);
if ($loginDetails != false)
{
if ($loginDetails['username'] == $username && $loginDetails['password'] == $password)
{
$this->load->view ('home');
}
else
{
$this->view();
echo "details dont match";
}
}
else
{
$this->view();
echo "nothing received from db";
}
}
else
{
$this->view();
echo "no details entered";
}
}
I am only concerned with going to the home page. By calling the view function I am just returning to the login screen. I will adjust the naming appropriately once I can get this to work. The pages model contains the following function to retrieve the login data from the database:
public function retrieveLoginDetails ($username, $password)
{
$loginDetails['username'] = $this->db->get_where('user_details', $username);
if (! empty ($loginDetails['username']))
{
$loginDetails['password'] = $this->db->get_where('user_details', $password);
return $loginDetails;
}
return false;
}
Any help would be greatly appreciated. Thanks.
Use
<input type="submit" value="Login" class="btn btn-lg btn-success btn-block" />
In place of
<a type="submit" id="login-button" style="navy" class="btn btn-lg btn-success btn-block">Login</a>
To know more check out this : http://www.w3schools.com/tags/tag_a.asp
I don't know direct anwser, but did you check what exactly is your server returning and where are data beeing sent. LiteBug FTW ;)
If there isn't any data beeing sent, you should probally check your .js files.

Yii login does not redirect to the page i want

I configured an Yii demo login application, by using its scripts and functions i tried to use it as the back end for the login page of my own website. which is html and its on a seperate directory.
It does get authenticated correctly but instead of redirecting to where i want after a successful login it goes to its own index of yii demo application. can anybody help on this to redirect to my own page.
<div class="col-xs-12 col-sm-12 col-md-5 col-lg-4">
<div class="well no-padding">
<form action="Login_yii/index.php?r=site/login" id="login-form" class="smart-form client-form">
<header>
Sign In
</header>
<fieldset>
<section>
<label class="label">Username</label>
<label class="input"> <i class="icon-append fa fa-user"></i>
<input type="text" name="LoginForm[username]" id="username">
<b class="tooltip tooltip-top-right"><i class="fa fa-user txt-color-teal"></i> Please enter the username</b></label>
</section>
<section>
<label class="label">Password</label>
<label class="input"> <i class="icon-append fa fa-lock"></i>
<input type="password" name="LoginForm[password]" id="password">
<b class="tooltip tooltip-top-right"><i class="fa fa-lock txt-color-teal"></i> Enter your password</b> </label>
<div class="note">
Forgot password?
</div>
</section>
<section>
<label class="checkbox">
<input type="checkbox" name="remember" checked="">
<i></i>Stay signed in</label>
</section>
</fieldset>
<footer>
<button type="submit" class="btn btn-primary" su>
Sign in
</button>
</footer>
</form>
Controller
<?php
class SiteController extends Controller
{
/**
* Declares class-based actions.
*/
public function actions()
{
return array(
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
// page action renders "static" pages stored under 'protected/views/site/pages'
// They can be accessed via: index.php?r=site/page&view=FileName
'page'=>array(
'class'=>'CViewAction',
),
);
}
/**
* This is the default 'index' action that is invoked
* when an action is not explicitly requested by users.
*/
public function actionIndex()
{
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
$this->render('index');
}
/**
* This is the action to handle external exceptions.
*/
public function actionError()
{
if($error=Yii::app()->errorHandler->error)
{
if(Yii::app()->request->isAjaxRequest)
echo $error['message'];
else
$this->render('error', $error);
}
}
/**
* Displays the contact page
*/
public function actionContact()
{
$model=new ContactForm;
if(isset($_POST['ContactForm']))
{
$model->attributes=$_POST['ContactForm'];
if($model->validate())
{
$name='=?UTF-8?B?'.base64_encode($model->name).'?=';
$subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';
$headers="From: $name <{$model->email}>\r\n".
"Reply-To: {$model->email}\r\n".
"MIME-Version: 1.0\r\n".
"Content-Type: text/plain; charset=UTF-8";
mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);
Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
$this->refresh();
}
}
$this->render('contact',array('model'=>$model));
}
/**
* Displays the login page
*/
public function actionLogin()
{
$form=new LoginForm;
// collect user input data
if(isset($_POST['LoginForm']))
{
$form->attributes=$_POST['LoginForm'];
// validate user input and redirect to previous page if valid
if($form->validate() && $form->login()) $this->redirect(Yii::app()->user->returnUrl);
}
// display the login form
$this->render('login',array('form'=>$form));
/*$model=new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login())
$this->redirect(Yii::app()->user->returnUrl);
}
// display the login form
$this->render('login',array('model'=>$model));*/
}
/**
* Logs out the current user and redirect to homepage.
*/
public function actionLogout()
{
Yii::app()->user->logout();
$this->redirect(Yii::app()->homeUrl);
}
}
file structure
index of my web and yii folder are highlighted
Ok You are redirecting to previous url (just before login) with if($form->validate() && $form->login()) $this->redirect(Yii::app()->user->returnUrl);
Redirect to Your URL of choice using CController::redirect()
See another question Yii not redirecting properly with the CController::redirect() function
In your site controller's login action just change the redirect from $this->redirect(Yii::app()->user->returnUrl); to $this->redirect(array("/<controller>/<action>"));
public function actionLogin()
{
$model=new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login())
$this->redirect(array("/<controller>/<action>"));//change the controller and action you want to redirect to.
}
// display the login form
$this->render('login',array('model'=>$model));
}

Categories