Codeigniter avoid re-submitting the form data - php

I am working with Codeigniter. I have a controller with the method named login which takes the form data and checks if user exists?, upon success it loads another view. But when I click the refresh button in my browser the method in my controller re-executes, I want to prevent the re-submission of form data. Kindly Help me. Also please suggest me how it should behave normally,whether it should just prevent the re-submission of form and stay insane or should it redirect to login screen.
here is the code :
Login Controller
<?php
class Login extends CI_Controller {
/**
*
* load the Models
*/
function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->model('User');
// $this->session->set_flashdata('success','data posted');
$this->load->library('session');
$this->load->helper('url');
}
public function index() {
$this->load->view('login');
}
/**
*
* Log in a user
*/
public function login() {
$this->form_validation->set_rules(array(
array(
'field' => 'username',
'label' => 'username',
'rules' => 'required|is_numeric|max_length[1]|min_length[1]',
),
array(
'field' => 'password',
'label' => 'password',
'rules' => 'required|is_numeric|max_length[1]|min_length[1]',
),
));
$this->form_validation->set_error_delimiters('<div class="alert alert-error">', '</div>');
//GETTING ID AND PASSWORD FROM THE FORM
$id = $this->input->post('username') . "<br>";
$password = $this->input->post('password') . "<br>";
//check if user exists
$user = new User();
$user_exists = $user->user_exists($id, $password);
//validate the user input
$validated = $this->form_validation->run();
if (!$validated) {
$this->load->view('login');
} else {
if ($user_exists) {
//use php function to pickup the current year from the pc
//set your min to 01-01-current year and your max to 31-12-current year
$min = strtotime(date('Y') . "-01-01");
$max = strtotime(date('Y') . "-12-31");
$date = rand($min, $max);
$dec2 = strtotime('2014-12-02');
$randomDate = date('Y-m-d', $date);
echo "random date:" . $randomDate . "<br>";
$date_timestamp = strtotime($randomDate);
if ($date_timestamp >= $dec2) {
$is_updated = $user->is_holiday_updated();
if (!$is_updated) {
// $user->update_national_holidays();
echo "holiday table updated";
} else {
echo "already updated the table";
}
} else {
echo "no update required";
}
$this->load->view('national_holiday_screen');
} else {
$this->load->view('login');
}
}
}
}
here is the View:
<h2> National Holiday Screen </h2>

You have to do like the following steps
in your model You have to create Method to check the username and password and in my example i will call that method Valid($username,$password);
this method will return true if matching db and false if not .
in your controller .
public function login()
{
// check if button is clicked by
if(isset($_POST['loginButton'])){
// check if username and password is correct
if($model->valid($this->input>post('username'),$this->input>post('password')){
//redirect to admin page
}else{
//load login form template
}
}else{
// load your login form template here
}
}
well , the main point here is that , to remove the post submitting from browser you have to redirect the user to another page as above example .
Note : your issue is with if statement you are displaying the template at end of the controller , you have to display the template base on if statement .

Related

PHP login using Ion Auth and Facebook login works locally on MAMP but not Web Server

The problem I'm facing is that manual new user subscription works locally but does not work on remote web server. The only difference between the non-working one and the one that works is that I upgraded Ion Auth to version 2 and added Facebook-Ion Auth library for Facebook Login.
Again, it works perfect locally, but not on the web server. PHP versions have been tested and work fine.
Here's the controller it gets stuck on (shows a blank page or goes back to homepage).
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Signup extends CI_Controller {
function __construct()
{
parent::__construct();
$this->CI =& get_instance();
$this->load->library('form_validation');
$this->load->helper('url');
$this->load->library('forms/signupform');
$this->form_validation->set_error_delimiters(
$this->config->item('error_start_delimiter', 'ion_auth'),
$this->config->item('error_end_delimiter', 'ion_auth')
);
}
/**
* #signup page of freelancer
*/
public function index()
{
$data['title'] = lang('title_registration');
$data['bodyclass'] = 'hold-transition register-page';
$data['js_bottom_files'] = array('plugins/iCheck/icheck.min', 'js/custom');
$data['cssfiles'] = array('plugins/iCheck/square/blue');
// POST SIGNUP FORM
if ('POST' == $this->input->server('REQUEST_METHOD') && $this->input->post('registersubmit') ) {
// Signup Action
$data['message_success'] = $this->signup();
}
// $user['checked'] = '';
// if ($this->input->post('agree') == 'yes') {
// $user['checked'] = 'checked';
// }
$data['form'] = $this->signupform->view($user);
//Render Or redirect according to User AccessLevel
if (!$this->ion_auth->logged_in()) {
$this->template->load('layout', 'home', $data);
} elseif ($this->ion_auth->is_admin()) {
redirect(site_url('admin/dashboard'), 'refresh');
} elseif ($this->ion_auth->is_members()) {
redirect(site_url('note/create'), 'refresh');
}
}
/**
* #Signup action for user
*/
public function signup()
{
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
// $this->form_validation->set_rules('full_name', lang('label_full_name'), 'required');
$this->form_validation->set_rules('loginPassword', lang('label_signup_createpassword'), 'required|min_length['.$this->config->item('min_password_length', 'ion_auth').']|max_length['.$this->config->item('max_password_length', 'ion_auth').']');
// $this->form_validation->set_rules('confirmpassword', lang('label_signup_confirmpassword'), 'required');
// $this->form_validation->set_rules('agree', 'Agree', 'required');
if ($this->form_validation->run() == true) {
$email = $this->input->post('email');
$password = $this->input->post('loginPassword');
// $additional_data = array('first_name' => $this->input->post('full_name'), 'school' => $this->input->post('school_name'));
$group_ids = array( 'user_groups' => 2);
if ($this->ion_auth->register($email, $password, $email, $additional_data, $group_ids)) {
//check to see if we are creating the user
//$this->session->set_flashdata('message_success', $this->ion_auth->messages());
//redirect(site_url('/'), 'refresh');
if($this->ion_auth->login($email, $password)){
redirect(site_url('note/create'), 'refresh');
}
} else {
$this->session->set_flashdata('message_error', $this->ion_auth->errors());
redirect(site_url('/'), 'refresh');
}
}
}
}
/* End of file signup.php */
Potentially not the issue without more information but:
$group_ids = array( 'user_groups' => 2); should just be $group_ids = array('2')
See usage of the register function here.
and in the Ion auth config file $config['identity'] should be set as email (if you haven't done so already).

Codeigniter ignoring a function?

I'm new to CodeIgniter and have only started learning ajax. I'm trying to make a web-based management system using codeigniter, a distant relative gave me a sample of his system using codeigniter for reference before he left to work abroad. but I'm having problem with the login page of his system it keeps on refreshing the login page.
here is the login page.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CM_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->generate_login_page('backbone/login', [
'title'=>'CCC case management system - Login',
'js'=>['modules/home/login.js']
]);
}
public function authenticate_login() {
//$this->output->set_content_type('json');
//$this->form_validation->set_rules('username', '<strong>Username</strong>', 'required');
//$this->form_validation->set_rules('password', '<strong>Password</strong>', 'required');
//if($this->form_validation->run()){
$input = elements(['username','password'], $this->input->post());
$input['username'] = ucwords($input['username']);
$input['password'] = sha1($input['password']);
$result = $this->login_model->check_user_exist($input['username']);
//echo $input['username'];
//echo $result;
if($input['username'] !== ''){
if($result)
{
$result_match = $this->login_model->check_user_password_match($input['username'],$input['password'] );
//echo ''.;
if($result_match)
{
$result_user = $this->login_model->retrieve_user_information($input['username']);
$user_type_id = 0;
$user_id = 0;
if($result_user->num_rows() > 0){
foreach ($result_user->result() as $row) {
$user_type_id = $row->user_type_id;
$user_id = $row->user_id;
$username = $row->username;
}
}
//echo json_encode($result_user);
$session_data = array(
'username' => $username,
'session_id' => $this->session->userdata('session_id'),
'user_id' => $user_id,
'user_type_id' =>$user_type_id,
'is_logged_in' => 1
);
$this->session->set_userdata($session_data);
$this->session->set_userdata('login_state', TRUE);
redirect('/');
}
else
{
$this->session->set_flashdata('msg', 'Incorrect Password or Username!');
redirect('login/');
//
//echo 'Username or Password is incorrect';
//$this->output->set_output($this->set_json_output(FALSE, 'Username or Password is incorrect'));
}
}
else
{
$this->session->set_flashdata('msg', 'Invalid Username or doesnt exist !');
redirect('login/');
//
//$this->output->set_output($this->set_json_output(FALSE, 'User not Exist'));
//echo 'User not registered';
}
}else{
$this->session->set_flashdata('msg', 'Please input username !');
redirect('login/');
}
/*}else{
$error_messages = array_values($this->form_validation->error_array());
$this->output->set_output($this->set_json_output(FALSE, $error_messages));
}*/
}
}
if username and password match from database is should redirect to another page. if not a message should pop out for incorrect user / pass.
im not getting any errors but the problem is it does not redirect to another page it only keeps on refreshing the page and also if i leave user and pass empty / give an incorrect user & pass input the same thing happens. it seems like the function authenticate_login is not being executed? can anyone tell me what exactly is wrong here. Tnx.

I get error when i login to my project and then go back to the base url

I'm getting error when login to my project and then goto the base url. The below is the error which i get
My Login page [ see the url ]
After logging in , if i remove the highlighted segments[pls see below image] after which i get the above error
I know these error are due to headers so can somebody help me in saying what error am i making in header. An also say how to make good use of session so that the form is to resubmitted when i refresh after logging in. Below are the header codes.
login header
<?php if(isset($this->session->userdata['logged'])){
header("location: http://localhost/capacity_planner/login/login_check");
}
?>
admin dashboard[after logging in header]
<?php if(isset($this->session->userdata['logged'])){
$email = ($this->session->userdata['logged']['email']);
}else{
header("location: http://localhost/capacity_planner/login");
}
?>
controller side
public function login_check(){
$data['base_url'] = base_url();
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if ($this->form_validation->run($this) == false) {
$this->index();
} else {
if(isset($this->session->userdata['logged'])) {
$data['login_bg'] = $this->input->post('login_bg');
$this->load->view("admin_db", $data);
}
}
function check_database($password){
$email= $this->input->post('email');
$user = $this->user->loginCheck($email, $password);
if($user[1] == 1){
$result = $this->user->user_details($email);
if($result != false) {
$session_data = array(
'id' => $result[0]->id,
'email' => $result[0]->cp_email,
);
$this->session->set_userdata('logged', $session_data);
return true;
}
} else{
$this->form_validation->set_message('check_database', $user[0]);
return false;
}
}
ERR_TOO_MANY_REDIRECTS is caused when strucked up in a conditional loop
I assume you want to redirect to admin dashboard if you go to index after logged in..
Try adding these lines in your public function index()
public function index(){
if(isset($this->session->userdata['logged'])) {
//admin_db display function eg.redirect('admindashboard');
}
else{
//load your index view
this->load->view('your_index_view');
}
}
or you can check reverse way in admin dashboard function like this
public function dashboard(){
if($this->session->userdata('logged') == ''){
redirect('index');
}
else{
$this->load->view('dashboard view');
}
}
This is my assumption.Kindly check it.

Captcha in Codeigniter can't verify text

I am trying to add a captcha for my login form in codeigniter.
The captcha is displaying fine. and problem is in verifying it.
When validate_captcha is being called the value from input post is correct but session value is new page value.(For example , if on the 1st page load captcha was 12345 (let's assume in second load it will be 54321) . then when in first load user inputs 12345 it will be checked with 54321.
What can I do?
Here is what I have tried
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller
{
public function index()
{
$capCode = rand(10000, 99999);
$this->session->set_userdata(array('captcha'=>$capCode));
echo $this->session->userdata['captcha'];//for debug only
$this->load->helper('captcha');
$vals = array(
'word' => $capCode ,
'img_path' => CAPTCHA_PATH,
'img_url' => base_url().CAPTCHA_PATH,
'img_width' => '150',
'img_height' => 30,
'expiration' => 1200
);
$cap = create_captcha($vals);
$data = array('un' => $un,'defTab'=>'','captcha'=>$cap);
$this->load->library('form_validation');
//I need to load different data if form is result of a post($data['defTab'])
if($this->input->post('submit'))
{
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('captcha', 'Captcha', 'required|callback_validate_captcha');
if ($this->form_validation->run() == FALSE)
{
$data['defTab'] = 'what i need';
$this->load->view('login',$data);
}
else
{
print_r($this->input->post());
}
}
else
{
$this->load->view('login',$data);
}
}
public function validate_captcha()
{
$sss=$this->input->post('captcha');
//I Use this line to find problem
$this->form_validation->set_message('validate_captcha', 'session:'.$this->session->userdata['captcha'].'\nPosted val:'.$sss);
if($sss!= $this->session->userdata['captcha'])
{
return false;
}
else
{
return true;
}
}
}
You have to set the session during creation of your form:
.
.
.
} else {
if (isset($cap["word"])) {
$this->session->set_userdata("word", $cap["word"]);
}
$this->load->view('login',$data);
}
And during the validation check it with:
if($this->input->post("word", TRUE) == $this->session->userdata("word")){
// do something
}
Before calling the create_captcha method use the below code to set the previous captcha
$this->session->set_userdata('prev_captcha',$this->session->userdata('captcha_word'));
provided captcha_word contains current captcha
and check like below
function checkCaptcha($str){
$word = $this->session->get('prev_captcha');
if(strcmp(strtoupper($str),strtoupper($word)) == 0){
return true;
}else{
return false;
}
}

Adding custom callback to Codeigniter Form Validation

I want to limit my registration to emails with #mywork.com I made the following in My_Form_validation.
public function email_check($email)
{
$findme='mywork.com';
$pos = strpos($email,$findme);
if ($pos===FALSE)
{
$this->CI->form_validation->set_message('email_check', "The %s field does not have our email.");
return FALSE;
}
else
{
return TRUE;
}
}
I use it as follows. I use CI rules for username and password and it works, for email it accepts any email address. Any I appreciate any help.
function register_form($container)
{
....
....
/ Set Rules
$config = array(
...//for username
// for email
array(
'field'=>'email',
'label'=>$this->CI->lang->line('userlib_email'),
'rules'=>"trim|required|max_length[254]|valid_email|callback_email_check|callback_spare_email"
),
...// for password
);
$this->CI->form_validation->set_rules($config);
The problem with creating a callback directly in the controller is that it is now accessible in the url by calling http://localhost/yourapp/yourcontroller/yourcallback which isn't desirable. There is a more modular approach that tucks your validation rules away into configuration files. I recommend:
Your controller:
<?php
class Your_Controller extends CI_Controller{
function submit_signup(){
$this->load->library('form_validation');
if(!$this->form_validation->run('submit_signup')){
//error
}
else{
$p = $this->input->post();
//insert $p into database....
}
}
}
application/config/form_validation.php:
<?php
$config = array
(
//this array key matches what you passed into run()
'submit_signup' => array
(
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|max_length[255]|valid_email|belongstowork'
)
/*
,
array(
...
)
*/
)
//you would add more run() routines here, for separate form submissions.
);
application/libraries/MY_Form_validation.php:
<?php
class MY_Form_validation extends CI_Form_validation{
function __construct($config = array()){
parent::__construct($config);
}
function belongstowork($email){
$endsWith = "#mywork.com";
//see: http://stackoverflow.com/a/619725/568884
return substr_compare($endsWith, $email, -strlen($email), strlen($email)) === 0;
}
}
application/language/english/form_validation_lang.php:
Add: $lang['belongstowork'] = "Sorry, the email must belong to work.";
Are you need validation something like this in a Codeigniter callback function?
$this->form_validation->set_rules('email', 'email', 'trim|required|max_length[254]|valid_email|xss_clean|callback_spare_email[' . $this->input->post('email') . ']');
if ($this->form_validation->run() == FALSE)
{
// failed
echo 'FAIL';
}
else
{
// success
echo 'GOOD';
}
function spare_email($str)
{
// if first_item and second_item are equal
if(stristr($str, '#mywork.com') !== FALSE)
{
// success
return $str;
}
else
{
// set error message
$this->form_validation->set_message('spare_email', 'No match');
// return fail
return FALSE;
}
}
A correction to Jordan's answer, the language file that you need to edit should be located in
system/language/english/form_validation_lang.php
not application/.../form_validation_lang.php. If you create the new file under the application path with the same name, it will overwrite the original in the system path. Thus you will lose all the usage of the original filters.

Categories