Set Header in CodeIgniter 4 - codeigniter

Hye guys.
Just need a help!!!
When I was using ci3 so I faced an issue when user clicked browser back button, that's show " resubmit the form", so I solved that issue after setting header in ci3. Now I upgrade my site ci3 to ci4 and again I m facing same issue. Can anyone plz convert this code in CI4?
CI 3 code in Controller construct
$this->output->set_header('Last-Modified:' . gmdate('D, d M Y H:i]') . 'GMT');
$this->output->set_header('Cache-Control: no-cache, must-revalidate');
$this->output->set_header('Cache-Control: post-check=0, pre-check=0', false);
$this->output->set_header('Pragma: no-cache');
CI 4 code in BaseController
$response->setHeader('Last-Modified',gmdate("D, d M Y H:i").'GMT');
$response->setHeader('Cache-Control', 'no-store');
$response->setHeader('Cache-Control', 'no-cache');
$response->setHeader('Cache-Control', 'must-revalidate');
$response->setHeader('Cache-Control', 'post-check=0');
$response->setHeader('Cache-Control', 'pre-check=0');
$response->setHeader('Pragma','no-cache');
$response->setHeader('Cache-Control', 'no-cache');
In CI 4 it is not working.
Any help will be appreciated.

Finally i got the solution and its working fine for me. i have just put these lines in BaseController.
$response->removeHeader('Cache-Control');
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");

You don't need to remove Cache-Control and use "native" header to assign it again.
I don't recommend this way unless you know exactly what you do and you should be confortble with the execution flow of responses mechanism in codeigniter or any other framework to avoid one of must heavy 500 errors .
Also in the your primary code you maybe overrid the value of cache controle again and again.
If you dealing with the same header name CI4 provide special method for that.
You set the header name and value then you apprend values as many as you need.
**Use semicolon only when you finish apprending values beacause you risk to overrid old value and this is mistakes in your code please follow the documentation **
You have to change your code like this:
For the same Header name use appendHeader method
$this->response->setHeader('Cache-Control', 'no-cache')
->appendHeader('Cache-Control', 'exemple .. post-check=0, pre-check=0...')
->appendHeader('Cache-Control', 'option 2')
->appendHeader('Cache-Control', 'option 3');
For other headers:
$this->response->setHeader('Last-Modified',gmdate("D, d M Y H:i").'GMT')
->setHeader('Header-Name-1', 'headear value')
->setHeader('Header-Name-2', 'headear value')
->setHeader('Header-Name-3', 'headear value')
->setHeader('Header-Name-4', 'headear value;');

Related

Scrapy: Check if response is an image

I need check if response is an image.
For requirements of the work I need to generate the url of the photos that can exist or no and record the url that contains an image.
When the url generated doesn't show a photo the response of the website is an html when the body is:
<body>No File Found</body>
also the response.status =200
The response header doesn't have a valuable info for both results with image and No File Found
For instance
HTTP/1.1 200 OK
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Transfer-Encoding: chunked
Expires: 0
Server: Microsoft-IIS/8.5
X-Powered-By: ASP.NET
X-Frame-Options: AllowAll
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: *
Date: Tue, 13 Aug 2019 01:44:40 GMT
The way that I found to check if the response is an image for this case was:
try :
no_file_found = response.xpath("/html/body[contains(., 'No File Found')]")
except:
photo_url = response.url
photo = PhotoItem()
photo['id'] = id
photo['url'] = photo_url
yield photo
Because When the response is an image the line
no_file_found = response.xpath("/html/body[contains(., 'No File Found')]")
throw this exception:
raise NotSupported("Response content isn't text")
I know that this isn't an elegant solution , but for this context it works
Question
My question is If there is another way more elegant to solve this problem, that not use try to solve that.
Notice that I don't need to download the image just need to record the valid url
Any suggestion is welcome.
Thanks in advance!!!
The simplest way would probably be to just check the type of the response:
from scrapy.http.response.text import TextResponse
if not isinstance(response, TextResponse):
# it's probably an image; do image stuff

what's the difference between Redirect and Response in laravel

In my project, I need to set a cookie, here is my first version:
$cookie = Cookie::make('from_app', 1);
$view = View::make('buy.sale')->with(array(
'goods' =>$goods_group,
'time' =>$time,
))->withCookie($cookie);
and I found that this cookie doesn't work.
and then here is the second version:
return Redirect::to($view)->withCookie($cookie)
and the cookie works but it will jump twice .
when I use
return Response::to($view)->withCookie($cookie)
everything is ok.
I don't know what version of Laravel are you using but on mine 4.2.15 there's not such thing like Response::to there's only Redirect::to and it creates a new redirect response to the given path.

Caching a redirect to a static image in Sinatra

I have a Sinatra route for displaying a status image. While this simple solution works, I run into caching issues:
get '/stream/:service/:stream_id.png' do
# Building image_url omitted
redirect image_url
end
What is a proper way to handle the caching here, to set a max TTL? These images will be embedded on other sites, otherwise I could simply link straight to the images I redirect to.
The problem is that it generates an URL like site.com/image.png which in turn redirects elsewhere -- but it's site.com/image.png that is considered cached by the browser, so it won't check if it's updated.
I've experimented a bit with Cache-Control headers, but I have yet to find a solution.
I'm open for other solutions if this method is completely boneheaded.
You set the Cache-Control on a per route basis:
get '/stream/:service/:stream_id.png' do
# Building image_url omitted
response['Cache-Control'] = "public, max-age=0, must-revalidate"
redirect image_url
end
You can also make use of Sinatra's expires method:
# Set the Expires header and Cache-Control/max-age directive. Amount
# can be an integer number of seconds in the future or a Time object
# indicating when the response should be considered "stale". The remaining
# "values" arguments are passed to the #cache_control helper:
#
# expires 500, :public, :must_revalidate
# => Cache-Control: public, must-revalidate, max-age=60
# => Expires: Mon, 08 Jun 2009 08:50:17 GMT
Or the cache_control method:
# Specify response freshness policy for HTTP caches (Cache-Control header).
# Any number of non-value directives (:public, :private, :no_cache,
# :no_store, :must_revalidate, :proxy_revalidate) may be passed along with
# a Hash of value directives (:max_age, :min_stale, :s_max_age).
#
# cache_control :public, :must_revalidate, :max_age => 60
# => Cache-Control: public, must-revalidate, max-age=60
#
# See RFC 2616 / 14.9 for more on standard cache control directives:
# http://tools.ietf.org/html/rfc2616#section-14.9.1
Sinatra Documentation (as of 1.4.6 release)
https://github.com/sinatra/sinatra/blob/v1.4.6/lib/sinatra/base.rb#L440
https://github.com/sinatra/sinatra/blob/v1.4.6/lib/sinatra/base.rb#L469

How to use last modified date to cache single page for 1 hour?

What I want to do is to cache a page for 1 hour. The thing is that I want to be able to set the case stale during this 1 hour period if my object is modified.
Here is my code so far:
$response = new Response();
$response->setLastModified(new \DateTime($lastModified));
if ($response->isNotModified($this->getRequest()))
return $response;
else
$response->setCache(array(
'public' => true,
'max_age' => 3600,
's_maxage' => 3600,
));
The problem is the above code doesn't check lastModified. Once the 1 hour cache is created I have to wait full 60 minutes to see the changes I have made to my object ($lastModified).
Here is an example of caching page using Last-Modified header at the symfony2 documentation.
I think your mistake is that you tries to use Last-Modified and then rewrite it with Cache-Control header (max_age, s_maxage).

Codeigniter not sending through JangoSMTP

I am trying to send an email using codeigniter through JangoSMTP and for whatever reason the script takes about 60-70 seconds then gives me an error on the last portion of the process, the send.
Here is CI's debug..
*220 relay.jangosmtp.net ESMTP Welcome to the JangoSMTP trackable email relay system.; Thu, 05 May 2011 19:08:15 -0000
hello: 250-relay.jangosmtp.net Hello netdesk.aiwebsystems.com [173.236.184.252], pleased to meet you.
250-ENHANCEDSTATUSCODES
250-SIZE
250-EXPN
250-ETRN
250-ATRN
250-DSN
250-CHECKPOINT
250-8BITMIME
250-AUTH CRAM-MD5 PLAIN LOGIN DIGEST-MD5
250-STARTTLS
250 HELP
from: 250 2.1.0 ... Sender ok
to: 250 2.1.5 ... Recipient ok; will forward
to: 250 2.1.5 ... Recipient ok; will forward
data: 354 Enter mail, end with "." on a line by itself
The following SMTP error was encountered:
Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method.
User-Agent: CodeIgniter
Date: Thu, 5 May 2011 14:08:16 -0500
From: "Ryan Thompson"
Return-Path:
To: service#aiwebsystems.com
Subject: =?utf-8?Q?Email_Test_SMTP?=
Reply-To: "service#aiwebsystems.com"
X-Sender: service#aiwebsystems.com
X-Mailer: CodeIgniter
X-Priority: 3 (Normal)
Message-ID: <4dc2f5a0b3518#aiwebsystems.com>
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8bit
Testing the email class.*
Here is the simple code I am using to send in a sandbox controller..
function smtp(){
$this->load->library('email');
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'relay.jangosmtp.net';
$config['smtp_user'] = 'MYUSERNAME';
$config['smtp_pass'] = 'MYPASS';
$this->email->initialize($config);
$this->email->from('myemail#aiwebsystems.com', 'Ryan Thompson');
$this->email->to('myemail#aiwebsystems.com');
$this->email->subject('Email Test SMTP');
$this->email->message('Testing the email class.');
$this->email->send();
echo $this->email->print_debugger();
}
I tested this exact same thing with my regular email host and creds and it popped one off perfectly.
I don't have any IP restrictions or From: restrictions at Jango. I am authing only as username/pass.
My CI Version is 2.0.0
I am at the end of my wits!! My Email.php class file is un-edited.
See here
The problem is likely due to the fact that CodeIgniter defaults to using LF as the line terminator, rather than CRLF required by RFC. Add this code:
$this->config['crlf'] = '\r\n';
$this->config['newline'] = '\r\n';

Resources