-3

We use header(); to redirect user.

This is used in very commonly in logging system too.

I have seen that many new PHP developers have used Code 1, but it is security wise very bad code since you can bypass the header redirect.


Question : I have curiosity to know that why official PHP team can't add exit() to inside header() ?.


If they added it, header() is securty wise good in default also.... But currently we need to add exit()....

Code 01

if(if logging is fail){
   header("Location: http://example.com/erro.php");
}

Code 02

if(if logging is fail){
   header("Location: http://example.com/erro.php");
   exit();
}
  • I don't ususally see this - nowadays I see ajax handling the error.. maybe just me? – treyBake Apr 03 '18 at 12:01
  • 5
    Because `header` function __sets headers__. And there're a lot of headers besides `Location` which can be set and they don't require `exit`. – u_mulder Apr 03 '18 at 12:02
  • @u_mulder Thanks. Can't they detect this is location header? – I am the Most Stupid Person Apr 03 '18 at 12:03
  • 3
    Perhaps you want to set the `Location` header *and* other headers and/or also send some response body. It's not up to the PHP devs to speculate what you want to do. – deceze Apr 03 '18 at 12:04
  • 2
    And what if you set more headers after setting `location` one? – u_mulder Apr 03 '18 at 12:04
  • You so lazy man, as mulder said there are multiple headers that can be use not only `Location`, but if you can code up-to 100's line then why can't you simply add exit, – Noman Apr 03 '18 at 12:06

2 Answers2

3

The core principle used when designing functions is single responsibility principle. Which means that function must do one action and do it good.

header function follows this principle. It sets a header. It doesn't care what happens next, it's not its' responsibility. That's why function header will never end a script.

If you want - you can create your own function:

function setLocationAndExit($location) {
    header('Location: ' . $location);
    exit();
}

And use it anywhere you want.

u_mulder
  • 54,101
  • 5
  • 48
  • 64
0

Because sometimes you can use header() without having to redirect, but to tweak a little bit your request.

For example, you could say to your server "hey, do not put my pages on cache please" for routes that you would like to no be able to be accessed without being logged. Featuring Laravel:

<?php

namespace App\Http\Middleware;

use Closure;

class DisableCache
{
    public function handle($request, Closure $next)
    {
        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");

        return $next($request);
    }
}

?>
Anwar
  • 4,162
  • 4
  • 41
  • 62