• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
codeigniter 4 session or cache issue

#1
I created a website using CI4 and it was working fine. On Wampserver its working fine. Now if change anything and update the server it shows the old data and session not working properly sometime. i think browser is caching the webpage. Is there any way to disable in CI4? is it cache issue or session? old data means if i change a css or a section of html it wont reflect the change. and old html shows.same for dynamic data.Cannot login,session not holding login details. for session iam using database. Everything works fine on local server.issue only on live server. iam using plesk hosting. Anyone have this issue? When tried on a new pc it works fine. And if any update made and try again issue comes initiated session in base controller.

Code:
$this->session = \Config\Services::session();

i use this in the controller for cache control

Code:
header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS');
//header("Cache-Control: public, max-age=60, s-maxage=60");
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.

App configuration for session:

Code:
    public $sessionCookieName  = 'ci_session';
    public $sessionSavePath = 'ci_sessions';
    public $sessionExpiration        = 7200;
    //public $sessionSavePath          = WRITEPATH . 'session';
    public $sessionMatchIP           = false;
    public $sessionTimeToUpdate      = 300;
    public $sessionRegenerateDestroy = false;

Tried Empty/Cache and hard reload. no caching is enable in the code
Edit: i checked the browser as mentioned in comment and its caching

Code:
cache-control: max-age=315360000
content-encoding: gzip
content-length: 9333
content-security-policy: upgrade-insecure-requests;
content-type: text/css
date: Thu, 14 Jan 2021 13:07:22 GMT
etag: "f0fc6fe8a1bdd61:0"
expires: Thu, 31 Dec 2037 23:55:55 GMT
last-modified: Wed, 18 Nov 2020 11:56:54 GMT
server: nginx
vary: Accept-Encoding
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-powered-by-plesk: PleskWin
x-sucuri-cache: HIT
x-sucuri-id: 18015
x-xss-protection: 1; mode=block

i dont know how this is caching.
the base controller

Code:
<?php
namespace App\Controllers;

/**
* Class BaseController
*
* BaseController provides a convenient place for loading components
* and performing functions that are needed by all your controllers.
* Extend this class in any new controllers:
*     class Home extends BaseController
*
* For security be sure to declare any new methods as protected or private.
*
* @package CodeIgniter
*/

use CodeIgniter\Controller;
use Config\Services;

header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.
class BaseController extends Controller
{

    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var array
     */
    protected $helpers = ['form', 'url','master'];
        protected $session;
    /**
     * Constructor.
     */
    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);

        //--------------------------------------------------------------------
        // Preload any models, libraries, etc, here.
        //--------------------------------------------------------------------
        // E.g.:
         $this->session = \Config\Services::session();
         date_default_timezone_set('Asia/Dubai');
                     $this->pager = \Config\Services::pager();
                   
                   

}
}

this is the login function

Code:
public function login($type = 0)
    {
        $session = session();
        $model = new HomeModel();
        $model1 = new CartModel;
        if ($this->request->getMethod() == 'post') {
            if (!$this->validate([
                'email' => [
                    'label' => 'Email',
                    'rules' => 'trim|required|is_not_unique[tbl_customers.email]',
                    'errors' => ['is_not_unique' => '{value}-Email is not registered with us']
                ],
                'current-password' => ['label' => 'Password', 'rules' => 'trim|required']
            ])) {
                $data['validation'] = $this->validator;
                $page = 'login_page';
                if (!is_file(APPPATH . '/Views/home/' . $page . '.php')) {
                    throw new \CodeIgniter\Exceptions\PageNotFoundException($page);
                }
                $data['title'] = ucfirst($page);

                return view('home/login_page', $data);
            } else {
                $status = $model->checkLogin($this->request->getVar());
                if (isset($status)) {
                    $session->remove('customerData');
                    session()->set('customerData', $status);
                    $cmsrDetails = session('customerData');
                    if (!empty(cart()->contents())) {
                        $cart = cart()->contents();
                        foreach ($cart as $key => $value) {
                            $is_exist = $model1->checkItems($value['rowid'], $cmsrDetails['customerID']);
                            if (!empty($is_exist)) {
                                if ($value['qty'] != 0) {
                                    $data = [
                                        'qty' => $value['qty']
                                    ];
                                    $model1->update($is_exist['id'], $data);
                                } else {
                                    $model1->delete($is_exist['id']);
                                }
                            } else {
                                $datain = [
                                    'CMid' => $cmsrDetails['customerID'],
                                    'rowId' => $value['rowid'],
                                    'itemId' => $value['id'],
                                    'qty' => $value['qty']
                                ];
                                $model1->insert($datain);
                            }
                        }
                    }
                    $getCart = $model1->CartItems($cmsrDetails['customerID']);
                    if (!empty($getCart)) {
                        $model1->UpdateCart($getCart);
                    }
                    return redirect()->to('/');
                } else {
                    $_SESSION['error'] = 'Username or Password incorrect';
                    $session->markAsFlashdata('error');
                }
            }
        }
        if (!empty(session('customerData'))) {
            return redirect()->to('/');
        }
        //$data['validation'] = $this->validator;
        $page = 'login_page';
        if (!is_file(APPPATH . '/Views/home/' . $page . '.php')) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException($page);
        }
        $data['title'] = ucfirst($page);
        echo view('home/login_page', $data);
    }
Reply

#2
1) If your using Chrome bring up the developer tools F12
2) Right click the circle in the top left toolbar
3) Click on Empty/Cache and hard reload.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply

#3
done.Still same.
its browser issue.
is there any way to stop browser from caching page in CI4?
Reply

#4
(01-09-2021, 07:00 AM)adil Wrote: done.Still same.
its browser issue.
is there any way to stop browser from caching page in CI4?

Why are you so convinced it’s a browser issue? What do you change on the server that is supposedly keep in the browser cache on is not refreshed? If it’s JS or CSS, it’s standard browser behavior and has nothing to do with CI. It it’s something else, it’s probably a bug in your code.
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
Reply

#5
i commented out some section in html and printed some variable in index controller print_r($data);exit;
Nothing is reflected.
i installed new browser and tried, it shows the changes I made.
Reply

#6
any suggestions on how to solve the issue?
Reply

#7
got almost working fine now.
added header() to controller and added 
Code:
class BaseController extends Controller
{
    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var array
     */
    protected $helpers = ['form', 'url', 'master'];
    protected $session;
    /**
     * Constructor.
     */
    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
         
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);
        //--------------------------------------------------------------------
        // Preload any models, libraries, etc, here.
        //--------------------------------------------------------------------
        // E.g.:
        $response->noCache();
        //print_r($response->getHeaders());exit;
        $this->session = \Config\Services::session();
        date_default_timezone_set('Asia/Dubai');
        $this->pager = \Config\Services::pager();
    }

to base controller.
still some caching reamining
when is try to get latest messages from user with  getMsgsByCustomer in below function
Code:
public function viewProfile($cID)
    {
      
        $data['states'] = states();
        $cmSerModel = new customerServiceModel;
        if (session('customerData')) {
            $data['customerDetails'] = $cmsrDetails = session('customerData');
            $data['msgs'] = $cmSerModel->getMsgsByCustomer($cmsrDetails['customerID']);
            $page = 'profilePage';
            if (!is_file(APPPATH . '/Views/home/' . $page . '.php')) {
                throw new \CodeIgniter\Exceptions\PageNotFoundException($page);
            }
            $data['title'] = "Customer Profile";
            echo view('home/profilePage', $data);
        } else {
            return redirect()->to('/');
        }
    }
in model
Code:
    public function getMsgsByCustomer($id = '')
    {
   
        $this->asArray();
        $this->where('customerID',$id);
        $query = $this->findAll();
       
      
        return $query;
    }

it still not showing updated messages.
Reply

#8
Because it doe's not know where to find this 

PHP Code:
$cmsrDetails['customerID'

It's not in that method so where is it?
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply

#9
(01-19-2021, 03:07 AM)InsiteFX Wrote: Because it doe's not know where to find this 

PHP Code:
$cmsrDetails['customerID'

It's not in that method so where is it?
it is from session after login in.
Code:
$data['customerDetails'] = $cmsrDetails = session('customerData');
session have customer details including "customerID".
only latest messages are not showing.older database entries are showing in webpage.
if i delete it any old entries from db it still show on webpage.
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.