Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - Should I call exit() after calling Location: header?

Tags:

php

After calling the redirect function header, should I call exit or not?

<?php // fileA $urlFailToGoTo = '/formerror.php';  if (sth) {    header(sprintf("Location: %s", $urlFailToGoTo));    exit(); //should I call exit() here? or return? }  ?> 

Thank you

like image 723
q0987 Avatar asked Aug 24 '10 05:08

q0987


People also ask

What does header () do in PHP?

The header() function in PHP sends a raw HTTP header to a client or browser. Before HTML, XML, JSON, or other output is given to a browser or client, the server sends raw data as header information with the request (particularly HTTP Request).

What is PHP header location?

One is header which starts with string “HTTP/” used to figure out the HTTP status code to send. Another one is the “Location” which is mandatory. replace: It is optional which indicates whether the header should add a second header or replace previous.


2 Answers

You definitely should. Otherwise the script execution is not terminated. Setting another header alone is not enough to redirect.

like image 78
rgroli Avatar answered Sep 19 '22 23:09

rgroli


You should, just like @rgroli explains. If you do not want to bother with brackets, you can also call header() IN exit():

if(sth) exit(header("Location: http://example.com")); 

Location header in HTTP/1.1 always requires absolute path see the note here.

Note: This is not a hack, since the exit code is used only if the parameter is integer, while header() produces void (it exits with code=0, normal exit). Look at it as exit_header() function like it should be after Location header.

like image 23
Jan Turoň Avatar answered Sep 19 '22 23:09

Jan Turoň