Ob_flush causes cloudflare to act weird

Here’s my code:

ignore_user_abort(true);
set_time_limit(0);
ob_start();
// do initial processing here
echo "content 1"; // send the response
header('Connection: close');
header('Content-Length: '.ob_get_length());
ob_end_flush();
ob_flush();
flush();
//do expensive processing here (user will never see this)
echo "content 2";

what this do is, to make php close connection early so user will not wait longer when the server do expensive processing.

If i refresh browser multiple times, sometimes it shows “content”, sometimes it shows “content 1”. Why is that?

If I turn off my cloudflare and refrsh the page multiple times it always shows “content 1” all the time.

Is this CF bug?

No, it is a bug in your code.

You cant send a certain content length and then add additional output and expect that to work. Drop the content length header and it might just work.

@sandro No its 100% not a bug.

see it here:
=> https://stackoverflow.com/a/14469376/11465104

The idea is, to make visitor not wait longer if the processing time takes for example 30 second.

I try it when cloudflare is turned off. and refresh try refresh it 50 times. it works showing “content 1” every single time.

When cloudflare is turned on. I refresh 50x it shows “content 1” 90% of the time. the other 10% shows just “content”

I like the certainty :wink:

I am afraid I have to spill the beans, just because something is on StackOverflow does not make it automatically right. Not only is the linked response seven years old (the question itself nine years) that very “solution” got quite a few comments about it not properly working.

The correct approach on how to implement that is the one actually marked as solution in that thread.

What you copy/pasted here is very unlikely to work reliably, particularly not in a proxied context.