If I ignore the 302, I see that redirect() stops output, but header() doesn't. redirect() uses header() to set the 302 response. Different behaviour, same function. What gives?
Some context: I'm building a site with CodeIgniter, and I'm playing with how the site should deal with guests and members.
Extending the CI Core:
class MY_Controller extends CI_Controller {
if (! $authenticated) redirect('/login');
}
Now a controller:
class Members_only extends MY_Controller {
function index()
{
// Display members only content
}
}
Then I thought, what if Alice (an unauthenticated visitor) ignores the 302 response? Can she see the rest of the content after the redirect? So I tested it, and now I'm totally confused. There's two functions that are available to me to send a 302 redirect.
header('Location: http://mywebsite.com/login', TRUE, 302);
And from CI's URL helper:
redirect('/login');
Here is what it looks like from the inside:
function redirect($uri = '', $method = 'location', $http_response_code = 302)
{
if ( ! preg_match('#^https?://#i', $uri))
{
$uri = site_url($uri);
}
switch($method)
{
case 'refresh' : header("Refresh:0;url=".$uri);
break;
default : header("Location: ".$uri, TRUE, $http_response_code);
break;
}
exit;
}
site_url() is returning "http://mywebsite.com/login".
Can someone point out what I'm missing here?
Do you see the exit in the CI redirect function? So whenever you use it, it will cause your application to stop processing whatever code you have left. This is the "different" behavior your are experiencing.
http://php.net/manual/en/function.exit.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With