phpcachingob-start

Understanding odd usage of ob_start()?


I found a video on utube concerning prevention of the warning:

"Warning: Cannot modify header information - headers already sent". at the following link:

https://www.youtube.com/watch?v=leIz1Q2LJr4

I looked at solutions on this site from years ago but none of them seem to work and this despite the fact that the solutions made sense.

However this utube solution which worked for me makes no sense and I was wondering if someone could explain why?

I could not open a new web page using header('location: filename'). I kept getting the warning. I added ob_start() to the beginning of my index page (the PHP section with header instruction, according to the video) and suddenly the warning went away and the page started opening. Why did this happen?

I thought ob_start() concerned the new page being opened and not the current active document?

I added here code below:

ob_start();
header('Content-Type: text/html');
header('X-Content-Type-Options: nosniff', false);
//stop cacheing of page
header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Pragma: no-cache"); // HTTP/1.0
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("X-XSS-Protection: 1");
header("X-Frame-Options: SAMEORIGIN");

Solution

  • The "Cannot modify header information" error occurs if anything gets output before http headers are sent.

    ob_start() starts a php feature called "output buffering" which will prevent php from directly outputting data (to the browser). Instead all output is "redirected" to a buffer and will only be turned into output if ob_flush()gets called which would in turn clear the buffer.

    In your example ob_start() "captures" any output created before headers are sent and solves your problem. As there is no ob_flush() in your script all formerly create output "vanishes".