Introduction
In this tutorial, we will learn how to solve the PHP header function problem. As a PHP dev, you have faced this problem many times when your header()
function does not redirect to the specified URL. See the code snippet in the code section of this tutorial to find the solution.
Using the Code
In the below code, we are trying to redirect to the website http://www.psychocodes.in using the PHP header()
function, but when we will run the script, we will get a warning saying that header is already sent. This is because in the below code, we have already sent the header as outputting the "hello world
" paragraph. So the web browser will not send the header again.
<!DOCTYPE html>
<html>
<head><title></title></head>
<body>
<p>Hello world</p>
<?php
header("Location:https://www.psychocodes.in");
?>
</body>
</html>
Solution to the Problem
To solve this problem, we have to store the header in a buffer and send the buffer at the end of the script, so to store the header in the buffer, we will use the php ob_start()
function and to clean the buffer, we will use the ob_end_flush()
function. See the below code snippet.
<?php
ob_start();
?>
<!DOCTYPE html>
<html>
<head><title></title></head>
<body>
<p>Hello world</p>
<?php
header("Location:https://www.psychocodes.in");
ob_end_flush();
?>
</body>
</html>
This is it! Now, you can successfully redirect where you want.
Points of Interest
I also faced the same problem with the header()
function but the error itself says the solution, so that's why we use ob_start()
function to store the header in a buffer and ob_end_flush()
function to clean it and send it when the whole execution is done.
History
I have put ob_end_flush
so that there will be no buffered input stored even after the execution is completed.