Server-Side Transfer in PHP

I couldn’t find this solution on the first page of Google search results, thus hoping this will help.

PHP doesn’t support something like ASP’s server-side transfer/redirect. This is due to the fact that PHP is built to support many different servers, and server-side redirect is actually a server-specific feature which is part of Microsoft IIS. PHP doesn’t have an abstraction to support redirect facilities of each different server. Let’s see how to work around that.

You’ve probably stumbled upon the header() PHP function.

header('Location: http://www.example.com/');

This function redirects you to a different page, but the catch is — it won’t work if you print‘ed, echo‘ed some output to the browser. The function actually modifies the HTML headers to include location. Headers are always sent to the browser before any content, and therefore it’s too late to modify them after output has started.

This isn’t very helpful, because you probably need to redirect somewhere in the middle of your script, possibly inside some condition. Fortunately, there is a quite simple solution for that.

Output Buffers Output Control Functions in PHP allow you to collect all output data into an output buffer before sending it to the browser.

In the very beginning of your script put the following:

This will tell PHP to collect your output into buffer instead of sending it to the user’s browser.

Now, you can print out anything all you want, until the time comes to redirect. When you need to redirect, all you have to do is the following:

ob_clean(); // this will clean your buffer, enabling you to send the headers
header('Location: http://www.example.com/'); // redirecting

You can put that into a condition, or anywhere you feel like. That’s all.

2 responses to “Server-Side Transfer in PHP”

  1. ChrisG

    great ^^

  2. Himanshu Parashar

    good blog ., with short and brief and correct data

Leave a Reply