Page refresh (F5) always causing form to submit - php

a bit new to CI, googled and overflowed alot and still got no answer
User enters site.
After succesful auth got redirected to main page
Link on the url stays the same with class/method
If u refresh page on a main - u always got question about repopulate form (chrome/firefox 100%)
the solution may be: after success redirect to another class or method
but i don't know how to do it, documentation seems more like reference to me
code is here: http://paste.ubuntu.com/696751/ line 28 - how to do redirect to another class or method with a redirection to another view too?

Well an example in CodeIgniter may be:
class login extends CI_Controller
{
function index ()
{
$this->load->library('form_validation');
$this->load->helper('url');
//Set form validation rules here: http://codeigniter.com/user_guide/libraries/form_validation.html
if ($this->form_validation->run() == TRUE)
{
//login user here
redirect('login/sucLogin'); // or just redirect to '/' if you want to send them to your home page
}
else
$this->load->view('loginForm'); //make form
}
function sucLogin ()
{
echo 'Successfully logged in';
echo anchor('/', 'Go Home');
}
}

Check to see if the user submitted the form
Validate the login credentials
Redirect on success
public function login()
{
if ($_POST)
{
$login = $this->input->post('login');
$password = md5($this->input->post('password'));
$q = $this->db
->where('login', $login)
->where('password', $password)
->limit(1)
->get('userbase');
if ($q->num_rows > 0 )
{
redirect('enter/main');
}
}
$returnlogin['login'] = $login;
$this->load->helpers('form');
$this->load->view('login_form',$returnlogin);
}
public function main()
{
$this->load->view('main');
}

Related

How to redirect back to previous page after login in Code Igniter?

Okay, so this is what I do:
I go to www.mywebsite.com/orders?id=1
It redirects be to login before proceeding.
I log in successfully but it redirects to www.mywebsite.com/orders.
If I am already logged in and go directly using GET method, it works fine. But if I am asked to login, the GET method disappears.
How do I preserve ?id=1?
Before redirecting the user back to the login page store the current page (the requested page) in a session variable. Assuming you have a function called check_login this would more or less look like what you should do:
public function check_login() {
if (!$this->session->has_userdata('logged_in') || $this->session->logged_in !== true) {
if (!empty($_SERVER['QUERY_STRING'])) {
$uri = uri_string() . '?' . $_SERVER['QUERY_STRING'];
} else {
$uri = uri_string();
}
$this->session->set_userdata('redirect', $uri);
redirect('/auth/login');
}
}
Then when the user successfully logs in your login function should somewhere have the following logic:
public function login() {
// form validation
// get post vars
// check username/pwd against db
if ($login) {
if ($this->session->has_userdata('redirect')) {
redirect($this->session->redirect);
} else {
redirect('/dashboard');
}
} else {
// error logging in
}
}
session variable could store the id.While log in using session pass the id value.You can retrive the value anywhere in session.
$this->load->library('session');
$this->session->set_userdata('userId', 'YourId');
where userId would be the name of the session variable, and YourId would be the value.
Simply Use this
redirect($_SERVER['HTTP_REFERER']);

CodeIgniter Ion Auth 2 Login AND Registration on single page

I am trying to run Ion Auth 2 login form and register user form on a single page (my home page), but no success. I tried to dublicate the code from create_account() function inside the login() function, but it doesnt work. I searched a lot for such an example, but nothing found for the two forms on one page. Can someone give me an advise or refference? Thank you very much in advance!
It is rather easy. You have two forms, and each of the forms is directed at a different controller function via the action attribute of the form. Those controller functions (let's call them login and register set flash messages and redirect back to the index auth controller (e.g. your homepage with the login and create user forms).
Here is an example using some of the code from https://github.com/benedmunds/CodeIgniter-Ion-Auth/blob/2/controllers/Auth.php
<?php
class Auth extends CI_Controller {
public function __construct() {
parent::__construct();
if ($this->ion_auth->logged_in()) {
// user logged in, redirect them to the dashboard
redirect('dashboard');
}
}
/**
* this page, /auth/ will have your forms and will
* submit to login() and register()
*
* login form action: /auth/login
* create account form action: /auth/register
*/
public function index() {
$data['message'] = $this->session->flashdata('message');
$this->load->view('login_and_create_user', $data);
}
public function login() {
// validate form input
$this->form_validation->set_rules('identity', str_replace(':', '', $this->lang->line('login_identity_label')), 'required');
$this->form_validation->set_rules('password', str_replace(':', '', $this->lang->line('login_password_label')), 'required');
if ($this->form_validation->run()) {
// 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)) {
$this->session->set_flashdata('message', $this->ion_auth->messages());
// if login is successful, redirect to dashboard
redirect('dashboard');
} else {
// login failed
$this->session->set_flashdata('message', $this->ion_auth->errors());
}
} else {
// form validation failed, redirect to auth with validation errors
$this->session->set_flashdata('message', validation_errors());
}
redirect('auth'); // redirect them back to the login/create user page
}
public function register() {
// same thing here for create logic
// validate, db, redirect
}
}

Codeigniter - Controller can't render view

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.

codeigniter session lost when refresh (F5)

First of all i'm new for codeigniter. All i want to ask is, why every refresh my session data is lost. i redirect to login.
Here is my code.
login controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
$this->load->helper('form');
$this->load->view('login');
}
}
?>
verifylogin
function index() {
//This method will have the credentials validation
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE) {
//Field validation failed. User redirected to login page
//$this->load->view('headerx');
//redirect('login', 'refresh');
$this->load->view('login');
}
else {
//Go to private area
redirect('home');
}
}
function check_database($password) {
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->user->login($username, $password);
if($result) {
$sess_array = array();
foreach($result as $row) {
$sess_array = array(
'id' => $row->id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else {
$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;
}
}
?>
home controller
function index()
{
if($this->session->userdata('logged_in')) {
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$this->load->view('home', $data);
}
else {
//If no session, redirect to login page
// print_r($this->session->all_userdata());
//die();
redirect('login');
}
}
first login it is success, but when i refresh (f5) it is back to login form.
my opinion its because session is lost.
thanks for any help...
EDIT AND SOLVED :
sorry for inconvenience, this problem happen because
<script>
function goOut(){
<?php $this->session->unset_userdata('logged_in');?>
window.location="<?php echo base_url()?>";
}
</script>
my purpose it is when click button logout, then session is unset, but if i input in the header, session will be lost again, so i will find another way. thank you for your attentions and help.
I would try using CodeIgniter's sessions in the database instead. I've had problems with CI in the past with this sort of problem. It usually occurs when you're setting a large amount of data (greater than 4KB) in the cookie.
Let me know if database-based sessions is not an option.
See here for more information: CodeIgniter Sessions See heading "Saving Session Data to a Database"
If you are on windows there is an issue with Codeigniter, PHP 7, and Apache on Windows 10. I had a client who wanted the staging application on their own laptop, and this only happened on their new laptop.
So after hours of testing, we uninstalled XAMPP 7.1.4, and reinstalled XAMPP with version 5.6.XX. And that fixed it. Yet, there were no issues on Linux boxes running Nginx and PHP 7. Just Windows 10.
Anyway, I hope this helps! It took me hours to find the solution.

codeigniter redirect fails only when i include "refresh"

<?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.

Categories