Pregunta

Does calling header('Location:') without die() after it make sense at all?

If not, why isn't die() being performed automatically by PHP interpreter? If yes, when?

¿Fue útil?

Solución

A good example is explained in this PHP user note, copied here for posterity:


A simple but useful packaging of arr1's suggestion for continuing processing after telling the the browser that output is finished.

I always redirect when a request requires some processing (so we don't do it twice on refresh) which makes things easy...

<?php 
 function redirect_and_continue($sURL) 
 { 
  header( "Location: ".$sURL ) ; 
  ob_end_clean(); //arr1s code 
  header("Connection: close"); 
  ignore_user_abort(); 
  ob_start(); 
  header("Content-Length: 0"); 
  ob_end_flush(); 
  flush(); // end arr1s code 
  session_write_close(); // as pointed out by Anonymous 
 } 
?>

This is useful for tasks that take a long time, such as converting a video or scaling a big image.

Otros consejos

header('Location: ') will make HTTP redirect that tells the browser to go to the new location:

HTTP/1.1 301 Moved Permanently
Location: http://example.com/another_page.php
Connection: close

It doesn't need any HTML body since the browser won't display it and just follow the redirection. That's why we call die() or exit() after header('Location:'). If you don't terminate the script, the HTTP response looks like this.

HTTP/1.1 301 Moved Permanently
Location: http://example.com/another_page.php
Connection: close

<!doctype html>
<html>
<head>
  <title>This is a useless page, won't displayed by the browser</title>
</head>
<body>
  <!-- Why do I have to make SQL queries and other stuff 
       if the browser will discard this? -->
</body>
</html>

why isn't die() being performed automatically by PHP interpreter?

The header() function is used to send raw HTTP header, not limited to header('Location:'). For example:

header('Content-Type: image/png');
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// ...more code...

In those situation we don't call die() since we need to generate HTTP response body. So it doesn't make sense if PHP automatically call die() after header().

In my personal opinion you should call die() at the point you don't want the script to be executed any more. If you don't want the script to be executed after your header("Location: ...") you should put die() right after it.

Basically if you don't do it, your script might do needless extra calculations, that never will be "visible" to the user since the server redirects him anyway.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top