Output Buffering for Header Redirection

Please follow and like us:
Pin Share
php, development, header
Output buffering for Header Redirection

So after I have managed a couple of co-located dedicated servers and used countless numbers of managed hosting control panels, I’ve landed on using a VPS (virtual private server) system. It seems, however, that there are some interesting things to know when you’re developing PHP applications as it relates to your server configuration. Something as simple as a header redirect can become an issue if you don’t have the right configuration of PHP.

Ok, I’ll back up a minute. You can use the header() function in PHP to redirect the user from one URL to another. In my case, I was writing a user authentication module and I wanted to redirect users to the login page if they weren’t logged in.

Here’s the code that I use to redirect my users to a login page:

header("Location: http://www.mywebsites/login");

As soon as I tried my redirect, which had worked many times before, I got the dreaded error message saying headers had already been sent. Now I knew better than to output any text of any kind before my redirect, so I always make sure to have my code do all its thinking before spitting out anything. The header code should have come first. Well, actually, it did.

However, the dedicated servers and other managed hosting I had used in the past always had a PHP.ini setting called “output_buffering” set to “on”. Here’s what it looks like:

output_buffering = On

After altering my PHP.ini configuration and setting “output_buffering” to “on”, my code worked exactly as it should and the whole world didn’t come to an abrupt end (although it felt like it for a sec).

If you need some help creating a PHP application and need a developer with years of experience who is also generally awesome, please feel free to drop me a line using the contact form below.’

 

[zee_button size=”lg” type=”primary” icon=”icon-envelope-alt” url=”/contact-me/” text=”Contact Me”]