by Mohd Shibli
Posted on 07 August 2016
While building a website or a web application a developer faces many problems and today i am going to share one of the most common problem which every php programmer faces while using the header() function, i faced this problem too in my early days of coding,
Let us first see what php header() function actually do, the header() function is used to redirect to a given url. The syntax for the header() function is shown below:
<?php header("Location:URL"); ?>
Now let us see a simple redirection script using php
<?php header("Location:http://www.psychocodes.in"); ?>
The above script will redirect you to www.psychocodes.in, now we will see what the problem actually is while using the header() function. When we are coding large applications sometimes we do the outputs before redirection due to which the output does not get stored in the buffer and the header function does not catch the URL due to which the redirection does not work.
So to solve this problem we need to store the output in a buffer and need to flush that buffer at the end of the code.
So we use a php function called ob_start() to buffer all the output of our php code and ob_end_flush() to flush all the output when the execution of the whole code is done.
So whenever you are facing such problem like your header() function is not redirecting then just follow this simple rule to solve it. Below is the code to show how to use ob_start() and ob_end_flush().
<?php ob_start(); //more code header("Location:URL"); ob_end_flush(); ?>
Just put the ob_start() function in the starting of your code and ob_end_flush() in the end. This will definetly solve your problem.
Thank you for reading.
Also, don't forget to subscribe to our Newsletter at top of this page.
If you like this article, then please share it and help us grow.
Preorder and Postorder Traversal of binary tree in Python
02 September 2018
Binary Tree in Python
02 September 2018
Explaining Register variables in C with examples
17 August 2018
Data Autosave System using PHP, MySQL and AJAX
06 July 2018