still very new to CodeIgniter and trying to do the following. I may be doing this wrong, and any direction, greatly appreciated.
I have a function that is called on submit of login form, validate_creds. If successful the form logs in, if not successful I want to set an $error_msg and reload the form. The validate_creds() appears to validate correctly but as you can see on the else statement I want to reload the index() passing the $error_msg displaying the message at the top of the form.
public function index($error_msg = '')
{
//data
$data['login'] = "Logged In";
if($error_msg !== '') {
$data['error_msg'] = $error_msg;
}
//view
$this->load->view('templates/login/login_header',$data);
$this->load->view('login/login_form', $data);
$this->load->view('templates/login/login_footer',$data);
}
public function validate_creds()
{
$this->load->model('user_model');
$query = $this->user_model->validate();
if($query)//if the users creds have been validated...
{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('gallery');
}
else
{
$error_msg = "Your username or password is not correct.";
$this->index($error_msg);
}
}
Form Message
<?php if($error_msg != ''): ?>
<div class="alert alert-error">
<?php echo $error_msg; ?>
</div>
<?php endif; ?>
What currently is happening is the $error_msg is displaying all the time.
I hope this is just how it came out with copy pasting because this code is hard to read. check out php codesniffer and as an industry standard, check out some documentation on zend about php code format.
so your logic requires the error message be injected into the index function (which I'm assuming is your action but just not labeled as so), and if it's not injected, it doesn't declare the error message because it's not injected.
i would look at $this->user_model->validate(); to ensure that's properly handling the http request (post).
Related
So I'm trying to build success page for user that successfully logged in by showing greet to the username like this
Hi, <username>
I've done this by calling session from controller. After log in, the username doesn't show up, but when I try to reload the page, it showed up. This is not right. Here's code in the view that called the session:
<div><p style="text-align: center;">Hi, <?php echo $this->session->userdata('uname'); ?></p></div>
And here's the set session code in controller:
//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->success();
}
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();
}
Anyone knows what should I do to fix this up?
Thank you.
UPDATE
The line in controller
redirect('page/success');
is calling success() method in my page.php controller. Code for success():
function success(){
$this->load->view('page_header');
$this->load->view('content_success');
$this->load->view('page_footer');
}
The content_success view is where I put the calling session for showing username.
I' facing a problem with trying to render login_view.php in my login.php controller. What I got is this error :
Firefox has detected that the server is redirecting the request for
this address in a way that will never complete.
This problem can sometimes be caused by disabling or refusing to accept cookies.
Here is my controller
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url','html'));
$this->load->library(array('session','form_validation'));
$this->load->database();
$this->load->model('user_model');
}
function index()
{
//get form input
$email = $this->input->post('email');
$password = $this->input->post('password');
//form validation
$this->form_validation->set_rules('email','Email-ID','trim|required|xss_clean');
$this->form_validation->set_rules('password','Password','trim|required|xss_clean');
if($this->form_validation->run() == FLASE)
{
//validation fail
$this->load->view('login_view');
}
else
{
//check user credentials
$uresult = $this->user_model->get_user($email, $password);
if(count($uresult)>0)
{
//set session
$sess_data = array('login' => TRUE, 'uname' => $uresult[0]->fname,'uid' => $uresult[0]->id);
$this->session->set_userdata($sess_data);
redirect('profile/index');
}
else
{
$this->session->set_flashdata('msg','<div class = "alert alert-danger text-center">Wrong Email/Password</div>');
redirect('login/index');
}
}
}
}
Please help me figure out whats the problem. Thank you.
I suggest you to load session library in autoload, since you will need it on other pages. Beside, you have a typo in the first if condition.
if($this->form_validation->run() == FLASE) // FIX FALSE
Fixed it! turns out I've mistaken using redirect instead of $this->load->view('login_view'); and $this->load->view('profile_view');
It seems if I use redirect and the code will always check if the if(count($uresult)>0) is TRUE or FALSE and then continue with the action, The redirect action will always runs. So it's endless loop.
Check out the check user credentials conditional statement.
I am developing a web application with codeigniter. I have a main screen which loads three views as follows:
1)header 2)main screen 3)footer
the 'main_screen' view loads another view called 'login'
here is the code
<?php
if($logged == null){
$CI = &get_instance();
$CI->load->view('login');
}else{
echo $logged;
$CI = &get_instance();
$CI->load->view('login');
}
?>
the variable $logged is actually a data sent by a controller, when I first time loads the page it gives error 'Undefined, variable', but when i login it doesn't, here is the code.
if($loginSucessfull){
$data['logged'] ='<div class="success">Login Sucessfull</div>';
$this->load->view('header');
//here I am sending data to the 'menu_screen'
$this->load->view('menu_screen',$data);
$this->load->view('footer');
} else {
$data['logged'] = '<div class="alert">Sorry the username or password is incorrect</div>';
$this->load->view('header');
//here again I am sending the data
$this->load->view('menu_screen',$data);
$this->load->view('footer');
}
What I am trying to do is, if the user is sucessfully logged in show the sucessfull message else show the error and the login form as well. please help me how to fix this.
$logged isn't null. You get the error because the variable does not exist.
You have to set $logged to something before the main_screen page loads.
I don't know whether it works or not. Just try:
data = array();
$data['logged'] = 'something that you want to assign';
I have an installation of Codeigniter, IonAuth + Hybridauth which I am reworking so my users can choose their own username instead of generating one using the first and last names returned by facebook.
So in my code below I check to see if a username was posted, if not I want to load the choose_username view but for some reason the view is not loading and its completely skipping that section which is why I added die('Why no view')
Update: This first piece of code runs fine in a new controller
Checkout the code here:
if(isset($_POST['username'])){
$username = $this->input->post('username', TRUE);
die($username);
}else{
$this->data['message'] = 'Please choose a username.';
$this->data['template'] = 'guests/partials/choose_username';
$this->load->view('guests/template/standard', $this->data);
die('Why no view?');
};
Longer version:
function login_provider($provider = '')
{
if(empty($provider)) redirect();
try
{
// create an instance for Hybridauth with the configuration file
$this->load->library('HybridAuthLib');
if ($this->hybridauthlib->serviceEnabled($provider))
{
// try to authenticate the selected $provider
$service = $this->hybridauthlib->authenticate($provider);
if ($service->isUserConnected())
{
// grab the user profile
$user_profile = $service->getUserProfile();
////////////
//var_dump($user_profile);
//die();
////////////
$provider_uid = $user_profile->identifier;
if($this->ion_auth->login_by_provider($provider,$provider_uid))
{
$data['user_profile'] = $this->ion_auth->user_by_provider();
//$this->load->view('auth/user_profile',$data);
$user = $this->ion_auth->user()->row();
//Redirect to custom subdomain
$url = explode('://',site_url());
if (strpos(site_url(),$user->username) !== false) {
redirect($url[0].'://'.str_replace('www','',$url[1]).'dashboard','refresh');
}
else{
redirect($url[0].'://'.$user->username.str_replace('www','',$url[1]).'dashboard');
};
}
else
{ // if authentication does not exist and email is not in use, then we create a new user
//Check if username was posted
if(isset($_POST['username'])){
$username = $this->input->post('username', TRUE);
die($username);
}else{
$this->data['message'] = 'Please choose a username.';
$this->data['template'] = 'guests/partials/choose_username';
$this->load->view('guests/template/standard', $this->data);
die('Why no view?');
};
So when I run the above code, all i get is a blank page with: Why no view.
As above, usually when I run into this sort of issue it's from a bug in the view code.
Also, I don't know what, is actually being passed by this post in the event of there not being username data but you might want to also be checking for an empty value for username. This is probably not the issue but it would be good to confirm that the initial if is evaluating the way you expect.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller
{
public function __construct()
{
parent::__construct();
//Model for fetching users in database
$this->load->model('user', '', TRUE);
}
public function index()
{
//Load method to help verify form credentials
$this->load->library('form_validation');
//-----------------------------------------------
//Verify Existance of values in login form fields
//-----------------------------------------------
//Validate existance of username field value
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
//Validate existance of password field value, and if exists then call 'check_database' func
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
//If the form validation is false (i.e. Missing form fields)
if($this->form_validation->run() == FALSE){
//Redirect back to login page
$this->load->view('general-Login');
}
//Login Success, goto main-page
else{
//Go to main page
redirect('Main', 'refresh');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//Check the username and password against database
$result = $this->user->login($username, $password);
//If there is a result
if($result){
//will be used for session information
$sess_array = array();
foreach ($result as $row){
$sess_array= array(
'id' => $row->id,
'username' => $row->username
);
//Session set as logged in
$this->session->set_userdata('logged_in', $sess_array);
}
return true;
}
//No existance of user or, incorrect password
else{
//Send Message of incorrect username or password
$this->form_validation->set_message('check_database', 'Invalid Username or Password');
return false;
}
}
}
So i have a verifylogin controller that handles the form data from my login page. Database access works great and everything works perfectly until i get to the redirect feature. I try to redirect with refresh and it just gives me a page that says "undefined". Now it will suddenly work when i remove the 'refresh' and just leave the controller name, but i'm trying to figure out why this 'refresh' won't work.
I've disabled my .htaccess
I've tried setting my $config['uri_protocol'] to REQUEST_URI, AUTO, and PATH_INFO
and had no luck.
Also, this is my first submission online to anything like a forum so please....be gentle.
First off, welcome to Stack Overflow.
Secondly, if redirect() without the "refresh" works, I would run with it and figure it out later.
For a deeper explanation, "refresh" attempts to do a meta-like refresh to the page similar to:
<meta http-equiv="refresh" content="0;URL='http://example.com/'">
(Note: It doesn't do that within your view, but rather sends the browser a similar snippet in the response)
What browser are you using? What version? Hopefully it's something up-to-date, because that could make a difference in how the refresh works.
I had similar problem. E.g. on my localhost refresh do not work and on the hosting provider settings it works. Maybe something in Apache/PHP configuration. Go without refresh, it is OK. I do not think it has something to do with a browser. I was using the same browser when that happened.