4

I have a very basic question... In a php function I'm redirecting if a value returns FALSE otherwise continuing the code.

flibbertigibbet()
{
   $value = true_or_false();

   if ($value == FALSE)
   {
       //redirect to another controller method
   }

   //the rest of the code
}

What happens after the redirect? Does the code break or does a little execute if say.. the redirect takes longer to load?

Is it good practice to use exit() after redirects?

CyberJunkie
  • 21,596
  • 59
  • 148
  • 215

3 Answers3

4

The code will continue to execute - not just when the redirect takes longer, but each time nd through to the end.

Whether you use exit() depends on whether or not you want the rest of the code to be executed. You might set a header() and send a new address, but you can still execute things afterwards - like updating a database or some other bits.

I normally think it is best to do all your required updating and send the header() right at the end of a page - makes debugging much easier and more intuitive.

Fluffeh
  • 33,228
  • 16
  • 67
  • 80
4

Just setting a redirect header does nothing on its own. ALWAYS exit or die after setting a Location header (unless you know exactly what you are doing)

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

It really depends on what you mean by redirect. Yes, it will never run the rest of the code if it's something like:
header("Location: http://newurl.com");

Otherwise, unless there's a good reason for it not to come back (infinate loops, you're trying to include content which is taking too long and have not set a timeout, you use an exit()...), then the rest of the code will be run as soon as the if condition code has finished running.

Adrien Hingert
  • 1,416
  • 5
  • 26
  • 51
  • 1
    Are you sure it will not run the rest of the code? That [sounds wrong to me](http://php.net/manual/en/function.header.php). Verify the claim perhaps? – Brad Koch Aug 19 '12 at 01:45
  • The code will still execute. You can test this really easily by sending two `header()` commands. The page will open to the second. – Fluffeh Aug 19 '12 at 01:54