Home > Software engineering >  After form submission,reloading page in codeigniter4 application, redirects to the page omitting the
After form submission,reloading page in codeigniter4 application, redirects to the page omitting the

Time:09-15

I developed a codeigniter4 application. The sign-in page I created is coded to redirect to itself after page submission using:

return $this->response->redirect(base_url('public/index.php/auth'));

The page redirects but after form submission, When I do a page reload, the browser asks for a confirm form resubmussion and on clicking continue, the page directs to <PROJECTROOT>/index.php/auth instead of <PROJECTROOT>/public/index.php/auth giving a 404 file not found error.

How does the public gets omitted here. How can I get the page reloaded correctly?

AuthController.php

<?php
namespace App\Controllers;
use Config\Services;
use App\Models\UserModel;

class Auth extends BaseController {


    // login
    public function index()
    {
       
        helper(['form']);
        
        $session = session();
      
        $email = $session->get('email');

       if ($email) {
       
           $password = $session->get('password');
           $this->chooseLoginTo($email,$password,$session);

       }
       else if($this->request->getVar('email')){
        
         $this->processLogin();
       }
       else {
         $this->_showLoginForm();
       }
    }
    
    public function processLogin()
    {
      helper(['form']);
      //set rules validation form
      $rules = [
          'email'         => 'required|min_length[6]|max_length[50]|valid_email',
          'password'      => 'required|min_length[6]|max_length[200]'
      ];

      if($this->validate($rules)){
        $this->_login();

      }
        else {
          $this->_showLoginForm();
        }
    }


    private function _showLoginForm()
    {
      $data['title'] = 'e-Ticketing Incident Reporting & Feedback IMS';
      $data['validation'] = $this->validator;

      //echo view('auth/login', $data);
        echo view('sign-in',$data);
    }

    /*public function xss_clean($data){
      $newdata=[];
      foreach($data as $key=>$value){
        $value = htmlentities($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');
        $newdata[$key]=$value;
      }
      return $newdata;
    }*/

    private function _login()
    {

        $session=session();
        $request = service('request');
        $email =$request->getVar('email');
        $password=$request->getVar('password');

        $this->chooseLoginTo($email,$password,$session);

    }

    public function chooseLoginTo($email,$password,$session){
        helper('my_helper');
      $model = new \App\Models\UserModel();
      $user = $model->where('email', $email)->first();
        //print_r($user);exit();
      if ($user) {
          if ($user['is_active'] == 1) {

              if (password_verify($password, $user['password'])) {

                  $data = [
                      'name' => $user['name'],
                      'email' => $user['email'],
                      'role_id' => $user['role_id'],
                      'logged_in' => TRUE
                  ];
                  
                  $data=xss_clean($data);
                 
                  $session->set($data);
                  if ($user['role_id'] == 1) {
                   
                      return $this->response->redirect(base_url('public/index.php/admin') );
                  } elseif($user['role_id'] == 3) {
                    return $this->response->redirect(base_url('public/index.php/report') );

                  
                  }
                  else{
                   
                    return $this->response->redirect(base_url('public/index.php/dashboard'));

                    
                  }
              }else{

                  $session->setFlashdata('msg', '<div  role="alert">

                  Wrong Password!</div>');
                  return $this->response->redirect(base_url('public/index.php/auth') );
                }
          } else {
                $session->setFlashdata('msg', '<div  role="alert">
              This email has not been activated yet!</div>');
              
              return $this->response->redirect(base_url('public/index.php/auth') );
            }
      } else {
            $session->setFlashdata('msg', '<div  role="alert">
          Email is not registered!</div>');
          
          return $this->response->redirect(base_url('public/index.php/auth') );
        }
    }
}

View: sign-in.php

<!--
=========================================================
* Soft UI Dashboard Tailwind - v1.0.4
=========================================================

* Product Page: https://www.creative-tim.com/product/soft-ui-dashboard-tailwind
* Copyright 2022 Creative Tim (https://www.creative-tim.com)
* Licensed under MIT (https://www.creative-tim.com/license)
* Coded by Creative Tim

=========================================================

* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="apple-touch-icon" sizes="76x76" href="../assets/img/apple-icon.png" />
    <link rel="icon" type="image/png" href="../assets/img/favicon.png" />
    <title><?=$title?></title>
    <!-- Fonts and icons -->
    <link href="https://fonts.googleapis.com/css?family=Open Sans:300,400,600,700" rel="stylesheet" />
    <!-- Font Awesome Icons -->
    <script src="https://kit.fontawesome.com/42d5adcbca.js" crossorigin="anonymous"></script>
   
    <!-- Nucleo Icons -->
    <link href="../assets/css/nucleo-icons.css" rel="stylesheet" />
    <link href="../assets/css/nucleo-svg.css" rel="stylesheet" />
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Main Styling -->

    <link href="../assets/css/soft-ui-dashboard-tailwind.css?v=1.0.4" rel="stylesheet" />

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script>
    <style>
    .errors {font-size:small;color:red;}
    .error {font-size:small;color:red;}
    .alert {font-size:small;color:red;}
    </style>
 
  </head>

  <body >
    <div >
      <div >
        <div >
          <!-- Navbar -->
          <nav >
            <div >
              <!--<a  href=""> <?=$title ?> </a>
              -->
              <h3 ><?= $title; ?></h1>

              <button navbar-trigger  type="button" aria-controls="navigation" aria-expanded="false" aria-label="Toggle navigation">
                <span >
                  <span bar1 ></span>
                  <span bar2 ></span>
                  <span bar3 ></span>
                </span>
              </button>
              <div navbar-menu >
                <ul >
                  <!--<li>
                    <a  aria-current="page" href="../pages/dashboard.html">
                      <i ></i>
                      Dashboard
                    </a>
                  </li>
                  <li>
                    <a  href="../pages/profile.html">
                      <i ></i>
                      Profile
                    </a>
                  </li>
                  <li>
                    <a  href="../pages/sign-up.html">
                      <i ></i>
                      Sign Up
                    </a>
                  </li>
                  <li>
                    <a  href="../pages/sign-in.html">
                      <i ></i>
                      Sign In
                    </a>
                  </li>-->
                </ul> 
                <!-- online builder btn  -->
                 <!--<li >
                  <a
                    
                    target="_blank"
                    href="https://www.creative-tim.com/builder/soft-ui?ref=navbar-dashboard&amp;_ga=2.76518741.1192788655.1647724933-1242940210.1644448053"
                    >Online Builder</a
                  >
                </li> -->
                <ul >
                  <li>
                    <a href="<?= base_url('public/index.php/auth/registration')?>" target="_blank" >Client Registration</a>
                  </li>
                </ul>
              </div> 
            </div>
          </nav>
        </div>
      </div>
    </div>
    
                                
    <?=form_open(base_url('public/index.php/auth'));
     ?>
    <main >
      <section>

        <div >
          <div >
            <div >
              <div >
                <div >
                  <div >
                    <h3 >Sign In Page</h3>
                    <p >Enter your email and password to sign in</p>
                  </div>
                  <!--<div  role="alert">
                  -->
                  <?= \Config\Services::validation()->listErrors(); ?>
                 <!-- </div> -->
                  
                                <span  id="res_message"></span>
                                <!--<div  role="alert">
-->
                                <?php if(session()->getFlashdata('msg')):?>
                                  <?= session()->getFlashdata('msg') ?>
                                  
                                <?php endif;
                                 unset($_SESSION['msg']);
                                ?>
                                <!--</div>-->
                  <div >
                    <form role="form">
                      <label >Email</label>
                      <div >
                        <input type="email" name="email"  placeholder="Email" aria-label="Email" aria-describedby="email-addon" />
                      </div>
                      <label >Password</label>
                      <div >
                        <input type="password" name="password"  placeholder="Password" aria-label="Password" aria-describedby="password-addon" />
                      </div>
                      <!--<div >
                        <input id="rememberMe"  type="checkbox" checked="" />
                        <label  for="rememberMe">Remember me</label>
                      </div>-->
                      <div >
                        <!--<button type="submit" >Sign in</button>-->
                        <input type="submit" name="submit" value="Sign In"  />  
                      </div>
                    </form>
                  </div>
                  <!--
                  <div >
                    <p >
                      Don't have an account?
                      <a href="../pages/sign-up.html" >Sign up</a>
                    </p>
                  </div> -->
                </div>
              </div>
              <div >
                <div >
                  <div  style="background-image: url('<?=base_url('public')?>/assets/img/curved-images/curved6.jpg')"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>
    <footer >
      <div >
        <!--<div >
          <div >
            <a href="javascript:;" target="_blank" > Company </a>
            <a href="javascript:;" target="_blank" > About Us </a>
            <a href="javascript:;" target="_blank" > Team </a>
            <a href="javascript:;" target="_blank" > Products </a>
            <a href="javascript:;" target="_blank" > Blog </a>
            <a href="javascript:;" target="_blank" > Pricing </a>
          </div>
          <div >
            <a href="javascript:;" target="_blank" >
              <span ></span>
            </a>
            <a href="javascript:;" target="_blank" >
              <span ></span>
            </a>
            <a href="javascript:;" target="_blank" >
              <span ></span>
            </a>
            <a href="javascript:;" target="_blank" >
              <span ></span>
            </a>
            <a href="javascript:;" target="_blank" >
              <span ></span>
            </a>
          </div>
        </div> -->
        <div >
          <div >
            <p >
              Copyright ©
              <script>
                document.write(new Date().getFullYear());
              </script>
              <?=$title;?> C-DIT
            </p>
          </div>
        </div>
      </div>
    </footer>
  </body>
  <script>
if ($("#login").length > 0) {
$("#login").validate({
rules: {
password: {
required: true,
},
email: {
required: true,
maxlength: 50,
email: true,
},
},
messages: {
password: {
required: "Please enter password",
},
email: {
required: "Please enter valid email",
email: "Please enter valid email",
maxlength: "The email name should less than or equal to 50 characters",
},
},
})
}
</script> 
  <!-- plugin for scrollbar  -->
  <script src="../assets/js/plugins/perfect-scrollbar.min.js" async></script>
  <!-- main script file  -->
  <script src="../assets/js/soft-ui-dashboard-tailwind.js?v=1.0.4" async></script>
</html>

.htaccess

<IfModule authz_core_module>
    Require all denied
</IfModule>
<IfModule !authz_core_module>
    Deny from all
</IfModule>

Routes.php

(app/Config/Routes.php)

$routes->get('/auth', 'Auth::index');
$routes->post('/auth', 'Auth::index'); 

CodePudding user response:

(AuthController.php)

Instead of:❌

return $this->response->redirect(base_url('public/index.php/auth'));

Use this:✅

return redirect()->back()->withInput();

Resources:

old($key[, $default = null[, $escape = 'html']])

redirect(string $route)

Addendum 1

Make sure your public/.htaccess file is similar to:

CodeIgniter4/public/.htaccess

Addendum 2

(View: sign-in.php)

Replace:

 <?=form_open(base_url('public/index.php/auth'));
     ?>

With:

<?= echo form_open('/auth'); ?>

Your HTML markup is quite messed up. You have a form_open(...) without a corresponding form_close(...) declaration.

In addition, you seem to have nested <form> tags, which doesn't make sense. You can't nest <form> tags. Can you nest HTML forms?

Your inner <form> tag also lucks an action="..." attribute.

Addendum 3

In your Controller, you seem to have a lot of Redirect routes in the form of: return $this->response->redirect(base_url('public/index.php/...'). Set up explicit user-defined routes in app/Config/Routes.php if you haven't done so already. In addition, in your Controller, replace all the Redirect routes with something similar to: return redirect()->to('/admin');

Addendum 4

(app/Config/Routes.php)

Ensure that auto-routing is disabled. I.e:

$routes->setAutoRoute(false);
  • Related