Session message repeat when click browser back - laravel

I want to show a session message after login. i do it using this
#if ($message = Session::get('success'))
<script>
toastr.success('{{ $message }}');
</script>
#endif
but when navigate another web page and click again browser back button . it shows previous session message . How can i remove session messages on browser back button.
I tried
{{ Session::forget('success') }}
it always forget session message. Even not display first time session.

Its because of cache.
you can use headers before sending response
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
There is a answer that can help you
prevent-browsers-back-button-login-after-logout-in-laravel

Related

Laravel 5 flash message flashes again after navigating away and using back button

In my controller im trying to redirect back with a Flash message in laravel 5. This all works great. The problem is no matter how i set it up the flash message always re-appears if i navigate away and then come back by using the browsers 'back button'.
So i have a users list with a delete button next to each user. When i click the delete button it calls my controller method to destroy. I made a little conditional in there that redirects back with an error if i am trying to delete an owner. I tried the following different ways to redirect back but with all i wind up with the same problem that the message shows again after navigating away and coming back via the browsers 'back button'.
1
return Redirect::route('users')->with('error_message', 'Some error msg');
2
Session::flash('error_message', 'Some error msg');
return Redirect::to('users');
In my view i pick it up like this:
#if (Session::has('error_message'))
{{ Session::get('error_message') }}
#endif
So that works good, i get the message. But as soon as for example i click a user in my user list to go to the details page and press the browser 'back button', the message flashes again. I dont get why it keeps flashing that data, i was under the impression that it just flashes one time.
Even if i try to clear it right after displaying (like below), it doesnt matter, it will always re-appear?
{!! Session::forget('error_message') !!}
Step 1 : create one middleware using following command:
php artisan make:middleware PreventBackHistory
Step 2:
replace content of PreventBackHistory.php with following content:
namespace App\Http\Middleware;
use Closure;
class PreventBackHistory {
/* Handle an incoming request.
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
return $response->header('Cache-Control','no-cache, no-store, max-age=0, must-revalidate')
->header('Pragma','no-cache')
->header('Expires','Sun, 02 Jan 1990 00:00:00 GMT');
}
}
step 3: register middleware in kernal.php
'preventBackHistory' => \App\Http\Middleware\PreventBackHistory::class,
step 4: use middleware in your controller's construstor
public function __construct()
{
$this->middleware('preventBackHistory');
$this->middleware('auth');
}
And good to go :)
Generally, when the user clicks the back button in the browser, the browser tries to display the contents of the previous page without reloading it. So it's likely not Laravel flashing to the session again, but the browser trying to help you out by caching the page for you.
For those of you not concerned with back button:
#if (Session::has('error_message'))
{{ Session::get('error_message') }}
{{ Session::forget('error_message') }}
#endif
and if that doesnt make it clear out, try:
#if (Session::has('error_message'))
{{ Session::get('error_message') }}
{{ Session::forget('error_message') }}
{{ Session::save() }}
#endif
You can show flash messages using javascript and use SessionStorage to stop repeating messages. Browser cache doesn't know if browser already shown a message, but we can use SessionStorage to check it before display.
<div id="flash-container"></div>
...
var popupId = "{{ uniqid() }}";
if(sessionStorage) {
// prevent from showing if it exists in a storage (shown);
if(!sessionStorage.getItem('shown-' + popupId)) {
$('#flash-container').append("<div>{{ session('status') }}</div>");
}
sessionStorage.setItem('shown-' + popupId, '1');
}
I've just come across this problem and I think the only way to get around it is to AJAX load your flash messages into the page.
I've not tested this yet but I assume that when the user goes back and the AJAX request fires the previous flash messages will have already been cleared.
Well it seems it was indeed the browser cache and after adding the code to stop cache it was ok and the message disappeared. It still is weird to me that i had to add this code to the controller to stop it from caching:
header('Cache-Control: no-store, private, no-cache, must-revalidate'); header('Cache-Control: pre-check=0, post-check=0, max-age=0, max-stale = 0', false);
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Expires: 0', false);
header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
header ('Pragma: no-cache');
Or this in the htaccess:
<IfModule mod_headers.c>
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires 0
</IfModule>
But that seemed a bit overkill to me ;)
Right now I am using Laravel8, And I got same problem.
But all solutions are outdated for latest version.
So, here is the solution for those people who are using Laravel8
#if(session('error'))
<div class="alert alert-danger mb-3">
{{ session('error') }}
{{ session()->forget('error') }}
</div>
#endif
session()->forget('error') will remove the session named error.
You can also remove multi session data or flash data.
like this - $request->session()->forget(['done', 'error', 'status']);

How to download files from db in codeigniter

I am creating a resource site for my campus where teachers upload files to folder and reference of that filed stored in db, and students can download those files using download option in student view side, and all these I have done in codeigniter using model view controller.
I need help for coding to download files. I managed to display a set of files but could not download yet, can anyone please help me with this? I'll be so thankful.
Try this
$download_file = 'C:\example.zip';//path of the file
$content_type = mime_content_type($download_file);//mime type of the file
$file_name = basename($download_file);//file name
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: ".$content_type);
header("Content-Disposition: attachment; filename=\"".$file_name."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($download_file));
while (ob_get_level()) {
ob_end_clean();
}
readfile($download_file);

Codeigniter Flash data not getting cleared

public function student_email()
{
$opt=$this->uri->segment(3);
$class=$this->input->post('class');
$edu_level=$this->input->post('edu_level');
$data=$this->newsletter_model->get_StudentData($opt,$class,$edu_level);
$subject=$this->input->post('txtSubjectRequired');
$message=$this->input->post('txtMessageRequired');
$message=nl2br($message);
$note="student";//Variable for Identifying Students alone
//Test Email
$email=$this->input->post('txtEmail');
if(trim($email)!=''){
$note="test";
$name="User";
$data=$email;
$this->sendMail($data,$subject,$message,$note,$name);
}
else {
//$this->sendMail($data,$subject,$message,$note,$text,$name='');
}
if($this->session->userdata('mail_status')=="success"){
$this->session->set_flashdata('success', 'Mail sent Successfully.');
}
else{
$this->session->set_flashdata('success', 'OOPS.! Mail Sending failed..!.');
}
$this->session->unset_userdata('mail_status');
redirect('/newsletter/student/'.$opt , 'refresh');
/**Note:
* Filter by field of study and Last topic need to be coded..
*/
}
When click the back button, flash data not getting cleared.
is it a cache problem..? any other
any solution instead of disabling cache?
Please help me with the solution..
<?php
header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
?>
I found this code
It solves the problem..

CI load view via jquery

hi guys im loading popup screen in this way
<script>
function show_popup(){
$('#popup-container').load(html);
$('.popup').fadeIn();
}
</script>
on my html
<a onlick="show_popup('popup/view-content')" href="#">
my problem is when the html was loaded the previous html loaded can be seen for awhile before the new one shows up.. how can i unload the previous html.
the view seems to cache displaying the previous html how can i erase the previous html then load the new one
To remove caching from a page you need to include this at the top of your page:-
$this->output->set_header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
$this->output->set_header("Last-Modified: " . gmdate("D, d M Y H:i(worry)") . " GMT");
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
$this->output->set_header("Cache-Control: post-check=0, pre-check=0", false);
$this->output->set_header("Pragma: no-cache");

Preventing ajax-jquery loaded external file from caching in IE

I have this jquery script to call an external file. So far so good. The script is working fine, but as always IE makes what he wants. The external file that I load with this script (weather.php) is a file with real-time weather conditions data in it. Whit this script, I can refresh the div inside which is my weather.php file. And obviously I don't want IE to cache the data in this file. I want when someone click on button "REFRESH", the included page to be reloaded with the new data in it. In IE this doesn't happens because of the cache.
How can I change this script to not cache the div's content, or how can I say to my included file (weather.php) to do not cache it self?
This is the script:
function ajax_request() {
$('#column_weather').html('<img src="../images/home/ajax-loader.gif" width="16" height="11" style="vertical-align:middle;"/><b> Loading...</b>');
$('#column_weather').load("../includes/home/weather.php");
}
`
And that's how I call the script:
Refresh`
Put a random variable on your query String
$('#column_weather').load("../includes/home/weather.php?myRand=" + guid());
I would make random var return a guid
function s4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
function() guid{
return s4()+s4()+"-"+s4()+"-"+s4()+"-"+s4()+"-"+s4()+s4()+s4();
}
Can't you just have proper caching instructions inside this weather.php file (to say not to cache it)
I would attach the current date and time as a GET parameter. Internet Explorer (and other browsers) view this information as critical to loading the page, just as any function returns a different value with different parameters. The trick is that you don't have to use the parameter. :)
$('#column_weather').load("../includes/home/weather.php?t=" + date());
Adding a random parameter to the end of the query URL will help, but try adding this to the beginning of weather.php:
<?php
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', FALSE);
header('Pragma: no-cache');
?>

Resources