0

I am using localhost to develop a website. Recently i was surprised that a script i was using was fully executed and then redirected using "header:('Location:http://....')" (with this being at the bottom). I was surprised because i had read the header needed to be at the top of the page before any output was called.

To see if there was a difference i then placed the header at the top of script. I was redirect fine but the script was not fully executed. I read up at "http://stackoverflow.com/questions/7213646/php-header-location-immediately" that i may "need ignore_user_abort() and with php-fpm it's fastcgi_finish_request‎() to guarantee entire script execution."

I am novel programmer and so if somebody could go into the how to do this that would be great, if it really is a necessity. However my first (and main) question is whether this is necessary as the script was working to start with. In order words, is this just an oddity with localhost, and thus i will need to go the more complicated route when i host the website properly?

Hector
  • 103
  • 2
  • 6
  • 13

1 Answers1

1

header()'s need to be sent before any other output is sent, this is not depended on the position in the code, but only of the fact if output was send before header() was used.

If you use any echo/print commands before sending the header, you will get an error.

One way to prevent output to be sent before you want it to, is to use output buffering (ob_start, ob_flush etc). See http://php.net/manual/en/function.ob-start.php.

output buffering will "store" all your output untill you are ready to send it, ie. after you send your headers.

Damien Overeem
  • 4,487
  • 4
  • 36
  • 55
  • I see. My script is simply performing a number of mysql queries to log user details (basically most of it is a visitor count function). Do mysql queries not count as output (seemingly not?) – Hector Dec 24 '12 at 11:56
  • nope, output includes anything redirected to the standard output, meaning echo or functions that print stuff (print_r for example). A Query returns an object and doesn't print anything to the standard output ^^ – Naryl Dec 24 '12 at 12:09