Ioncannon Ioncannon - 1 month ago 17
HTTP Question

How to disable output buffering in PHP

I wrote a simple relay script that connects to a web camera and reads from the socket, and outputs this data using the print function. The data is MJPG data with boundaries already setup. I just output the data that is read.

The problem is PHP seems to be buffering this data. When I set the camera to 1 FPS, the feed will freeze for 7-8 seconds, then quickly display 8 frames. If I set the resolution to a huge size, the camera move at more or less 1 frame per second. I assume then some buffering is happening (since huge sizes fill the buffer quickly, and low sizes don't), and I can't figure out how to disable this buffering. Does anyone know how to?

Code:

ignore_user_abort(false);

$boundary = "myboundary";

//Set this so PHP doesn't timeout during a long stream
set_time_limit(0);

$socketConn = @fsockopen ("192.168.1.6", 1989, $errno, $errstr, 2);
if (!$socketConn)
exit();
stream_set_timeout($socketConn, 10);
fputs ($socketConn, "GET /mjpeg HTTP/1.0\r\n\r\n");

//Setup Header Information
header("Cache-Control: no-cache");
header("Cache-Control: private");
header("Pragma: no-cache");
header("Content-type: multipart/x-mixed-replace; boundary=$boundary");

@ini_set('implicit_flush', 1);
for ($i = 0; $i < ob_get_level(); $i++)
ob_end_flush();
ob_implicit_flush(1);

stream_set_blocking($f2, false);

//Send data to client
while (connection_status() == CONNECTION_NORMAL)
{
$chunk = fread($socketConn, 128);
print $chunk;
}

fclose($socketConn);

Answer

Rather than disabling output buffering, you can just call flush() after every read operation. This avoids having to mess with the server configuration and makes your script more portable.

Comments