Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid browser cache using Codeigniter

Facing issue related to browser chache.

function doUpload(){

  $data['includeView'] = "profileconfirm";

 $config['upload_path'] = './img/images/uploaded/';
 $config['allowed_types'] = 'gif|jpg|png|jpeg';
 $config['max_size'] = '5000';
 $config['max_width']  = '1024';
 $config['max_height']  = '768';
 $config['file_ext'] =".jpeg";
 $config['file_name'] = $profileId.$config['file_ext'];
 $config['overwrite'] = TRUE;
 $this->load->library('upload', $config);

 $query = null ; 

 if ( ! $this->upload->do_upload()){
  // Error here
 }else{
 // Image uploaded sucess fully
 // $profile - business logic to populate $profile

  $data['PROFILE_DETAILS'] = $profile;

 $this->load->view('index', $data);
}

this method is used for image upload. After successful image upload, it loads index view page, which internally includes profileconfirm view page.

But on profileconfirm page new uploaded image is not going to reflect. Some times it works fine, but some times not, this is happen most of the times.

Please help

like image 523
Vicky Avatar asked Dec 05 '22 23:12

Vicky


2 Answers

You can send proper headers to the client to disable the cache:

....
$this->output->set_header("HTTP/1.0 200 OK");
$this->output->set_header("HTTP/1.1 200 OK");
$this->output->set_header('Last-Modified: '.gmdate('D, d M Y H:i:s', $last_update).' GMT');
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate");
$this->output->set_header("Cache-Control: post-check=0, pre-check=0");
$this->output->set_header("Pragma: no-cache");
$this->load->view('index', $data);

Note: Output class is initialized automatically

like image 189
Francesco Laurita Avatar answered Dec 10 '22 10:12

Francesco Laurita


Just add a timestamp to the src attribute of the image being displayed.

<img src="filename.jpg?<?php echo time(); ?>">

To disable the cache completely with one line of code (after extending the Output library) review http://www.robertmullaney.com/2011/08/13/disable-browser-cache-easily-with-codeigniter/
Disclaimer, my blog

Edit 1: The accepted solution is overkill in my opinion when all you want to do force-reload the image in the browser ;)
Edit 2: Simplified the suggested solution.

like image 40
Mavelo Avatar answered Dec 10 '22 11:12

Mavelo