Php. Should I call exit () after calling the Location: header?

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

+64
php
Aug 24 '10 at 5:02
source share
5 answers

You definitely should. Otherwise, the script does not complete. Setting another header is not enough for redirection.

+71
Aug 24 '10 at 5:05
source share
β€” -

You should, as @rgroli explains. If you don't want to worry about parentheses, you can also call header() IN exit() :

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

The header header in HTTP / 1.1 always requires an absolute path; see note here .

Note: This is not a hack, because the exit code is used only if this parameter is an integer and header() is void (it exits with code = 0, normal exit). Look at it as the exit_header() function, as it should after the Location header.

+26
Aug 24 '10 at 10:12
source share

Generally good practice for exit; (note this is a keyword, so you don't need () ) after sending the Location: header, since browsers should be redirected to a new page, and so on, running the current script is usually undesirable.

+18
Aug 24 '10 at 5:03
source share

If you do not have the code (PHP or HTML) under the heading, you do not need to.

+8
Aug 24 '10 at 5:29
source share

the output is poor coding.

If you are ever developing a large project and want to create PHP Unit test modules, the output will ruin you.

exit exits the script and your current test! there is no way to restore the test and say that it failed or not ...

organize your code so that there is no way out, and the script ends naturally if you use redirection ...

+5
May 14 '14 at 13:55
source share



All Articles