ob_start

(PHP 4, PHP 5, PHP 7, PHP 8)

ob_startActiva el almacenamiento en búfer de la salida

Descripción

ob_start(callable $output_callback = null, int $chunk_size = 0, int $flags = PHP_OUTPUT_HANDLER_STDFLAGS): bool

Esta función activará el almacenamiento en búfer de la salida. Mientras dicho almacenamiento esté activo, no se enviará ninguna salida desde el script (aparte de cabeceras); en su lugar la salida se almacenará en un búfer interno.

El contenido de este búfer interno se puede copiar a una variable de tipo string usando ob_get_contents(). Para producir la salida de lo almacenado en el búfer interno se ha de usar ob_end_flush(). De forma alternativa, ob_end_clean() desechará de manera silenciosa el contenido del búfer.

Advertencia

Algunos servidores web (p.ej. Apache) cambian en directorio de trabajo de un script cuando se invoca a la función de llamada de retorno. Se puede cambiar de nuevo mediante, por ejemplo, chdir(dirname($_SERVER['SCRIPT_FILENAME'])) en la función de llamada de retorno.

Los búferes de salida son apilables, es decir, que se podría llamar a ob_start() mientras otro ob_start() esté activo. Se ha de asegurar llamar a ob_end_flush() las veces apropiadas. Si están activas múltiples funciones de llamada de retorno de salida, la salida se filtrará secuencialmente por cada una de ellas en orden de anidamiento.

Parámetros

output_callback

Se puede especificar una función output_callback opcional. Esta función toma un string como parámetro y debería devolver otro string. La función se llamará cuando el búfer de salida sea volcado (enviado), limpiado (con ob_flush(), ob_clean() o alguna función similar) o cuando el búfer de salida sea volcado al navegador al final de la petición. Cuando se llame a output_callback, ésta recibirá el contenido del búfer de salida como su propio parámetro, y se espera que devuelva un nuevo búfer de salida como resultado, que será enviado al navegador. Si output_callback no es una función llamable, esta función devolverá false. Esta es la firma de la llamada de retorno:

handler(string $buffer, int $phase = ?): string
buffer
Contenido del búfer de salida.
phase
Máscara de bits de constantes PHP_OUTPUT_HANDLER_*.

Si output_callback devuelve false, se enviará la entrada original al navegador.

El parámetro output_callback se puede omitir pasando un valor null.

ob_end_clean(), ob_end_flush(), ob_clean(), ob_flush() y ob_start() no se pueden llamar desde una función de llamada de retorno. Si se hace, el comportamiento no estará definido. Si se quiere borrar el contenido de un búfer, se ha de devolver "" (un string nulo) desde la función de llamada de retorno. Tampoco se pueden llamar a funciones usando las funciones de búfer de salida como print_r($expresión, true) o highlight_file($nombre_fichero, true) desde una función de llamada de retorno.

Nota:

En PHP 4.0.4, ob_gzhandler() se introdujo para facilitar el envío de datos codificados con gz a los navegadores web que admitan páginas web comprimidas. ob_gzhandler() determima el tipo de codificación de contenido que aceptará el navegador y devolverá su salida en consecuencia.

chunk_size

Si se proporciona el parámetro opcional chunk_size, el búffer será volcado después de cualquier llamada de salida que cause que la longitud del búfer sea igual o exceda a chunk_size. El valor predeterminado 0 significa que la función de salida será llamada únicamente cuando el búfer de salida se cierre.

Antes de PHP 5.4.0, el valor 1 era un caso especial que establecía el tamaño de segmento a 4096 bytes.

flags

El parámetro flags es una máscara de bits que controla las operaciones que se pueden realizar sobre el búfer de salida. Lo predeterminado es permitir que los búferes de salida sean limpiados, volcados y borrados, lo que se puede hacer explícitamente mediante PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_FLUSHABLE | PHP_OUTPUT_HANDLER_REMOVABLE, o PHP_OUTPUT_HANDLER_STDFLAGS como clave.

Cada bandera (flag) controla el acceso a un conjunto de funciones, como está descrito a continuación:

Constante Funciones
PHP_OUTPUT_HANDLER_CLEANABLE ob_clean(), ob_end_clean(), y ob_get_clean().
PHP_OUTPUT_HANDLER_FLUSHABLE ob_end_flush(), ob_flush(), y ob_get_flush().
PHP_OUTPUT_HANDLER_REMOVABLE ob_end_clean(), ob_end_flush(), y ob_get_flush().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión Descripción
7.0.0 En caso de utilizar ob_start() dentro de una retrollamada del búfer de salida, esta función ya no emitirá un E_ERROR, si no un E_RECOVERABLE_ERROR, permitiendo a los manejadores de errores propios capturar tales errores.
5.4.0 El tercer parámetro de ob_start() se cambió de un parámetro boolean llamado erase (el cual, si se establecía a false, prevenía al búfer de salida de ser eliminado hasta el final de la ejecución del script) a un parámetro integer llamado flags. Desafortunadamente, esto resulta en una rotura de compatibilidad de la API para código escrito antes de PHP 5.4.0 que use el tercer parámetro. Véase el ejemplo de banderas para saber cómo manejar esto con código que necesite ser compatible con ambas.
5.4.0 Un tamaño de segmento de 1 ahora resulta en segmentos de 1 byte que se van a enviar al búfer de salida.
4.3.2 Se modficó esta función que devuelva false en caso de que la función output_callback pasada no pueda ejecutarse.

Ejemplos

Ejemplo #1 Ejemplo de una función de llamada de retorno definida por el usuario

<?php

function callback($búfer)
{
// reemplazar todas las manzanas por naranjas
return (str_replace("manzanas", "naranjas", $búfer));
}

ob_start("callback");

?>
<html>
<body>
<p>Es como comparar manzanas con naranjas.</p>
</body>
</html>
<?php

ob_end_flush
();

?>

El resultado del ejemplo sería:

<html>
<body>
<p>Es como comparar naranjas con naranjas.</p>
</body>
</html>

Ejemplo #2 Crear un búfer de salida imborrable de forma compatible con PHP 5.3 y 5.4

<?php

if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
ob_start(null, 0, PHP_OUTPUT_HANDLER_STDFLAGS ^
PHP_OUTPUT_HANDLER_REMOVABLE);
} else {
ob_start(null, 0, false);
}

?>

Ver también

  • ob_get_contents() - Devolver el contenido del búfer de salida
  • ob_end_clean() - Limpiar (eliminar) el búfer de salida y deshabilitar el almacenamiento en el mismo
  • ob_end_flush() - Volcar (enviar) el búfer de salida y deshabilitar el almacenamiento en el mismo
  • ob_implicit_flush() - Habilitar/deshabilitar el volcado implícito
  • ob_gzhandler() - ob_start callback function to gzip output buffer
  • ob_iconv_handler() - Convierte la codificación de caracteres al manejador del buffer de salida
  • mb_output_handler() - Función de llamada de retorno que convierte la codificación de caracteres en búfer de salida
  • ob_tidyhandler() - Función callback de ob_start para reparar el buffer

add a note

User Contributed Notes 6 notes

up
53
Ray Paseur (Paseur ... ImagineDB.com)
19 years ago
You can use PHP to generate a static HTML page. Useful if you have a complex script that, for performance reasons, you do not want site visitors to run repeatedly on demand. A "cron" job can execute the PHP script to create the HTML page. For example:

<?php // CREATE index.html
ob_start();
/* PERFORM COMLEX QUERY, ECHO RESULTS, ETC. */
$page = ob_get_contents();
ob_end_clean();
$cwd = getcwd();
$file = "$cwd" .'/'. "index.html";
@
chmod($file,0755);
$fw = fopen($file, "w");
fputs($fw,$page, strlen($page));
fclose($fw);
die();
?>
up
20
net_navard at yahoo dot com
18 years ago
Hello firends

ob_start() opens a buffer in which all output is stored. So every time you do an echo, the output of that is added to the buffer. When the script finishes running, or you call ob_flush(), that stored output is sent to the browser (and gzipped first if you use ob_gzhandler, which means it downloads faster).

The most common reason to use ob_start is as a way to collect data that would otherwise be sent to the browser.

These are two usages of ob_start():

1-Well, you have more control over the output. Trivial example: say you want to show the user an error message, but the script has already sent some HTML to the browser. It'll look ugly, with a half-rendered page and then an error message. Using the output buffering functions, you can simply delete the buffer and sebuffer and send only the error message, which means it looks all nice and neat buffer and send
2-The reason output buffering was invented was to create a seamless transfer, from: php engine -> apache -> operating system -> web user

If you make sure each of those use the same buffer size, the system will use less writes, use less system resources and be able to handle more traffic.

With Regards, Hossein
up
28
ed.oohay (a) suamhcs_rodnan
21 years ago
Output Buffering even works in nested scopes or might be applied in recursive structures... thought this might save someone a little time guessing and testing :)

<pre><?php

ob_start
(); // start output buffer 1
echo "a"; // fill ob1

ob_start(); // start output buffer 2
echo "b"; // fill ob2
$s1 = ob_get_contents(); // read ob2 ("b")
ob_end_flush(); // flush ob2 to ob1

echo "c"; // continue filling ob1
$s2 = ob_get_contents(); // read ob1 ("a" . "b" . "c")
ob_end_flush(); // flush ob1 to browser

// echoes "b" followed by "abc", as supposed to:
echo "<HR>$s1<HR>$s2<HR>";

?></pre>

... at least works on Apache 1.3.28

Nandor =)
up
6
Asher Haig (ahaig at ridiculouspower dot com)
17 years ago
When a script ends, all buffered output is flushed (this is not a bug: http://bugs.php.net/bug.php?id=42334&thanks=4). What happens when the script throws an error (and thus ends) in the middle of an output buffer? The script spits out everything in the buffer before printing the error!

Here is the simplest solution I have been able to find. Put it at the beginning of the error handling function to clear all buffered data and print only the error:

$handlers = ob_list_handlers();
while ( ! empty($handlers) ) {
ob_end_clean();
$handlers = ob_list_handlers();
}
up
7
Chris
14 years ago
Careful with while using functions that change headers of a page; that change will not be undone when ending output buffering.

If you for instance have a class that generates an image and sets the appropriate headers, they will still be in place after the end of ob.

For instance:
<?php
ob_start
();
myClass::renderPng(); //header("Content-Type: image/png"); in here
$pngString = ob_get_contents();
ob_end_clean();
?>

will put the image bytes into $pngString, and set the content type to image/png. Though the image will not be sent to the client, the png header is still in place; if you do html output here, the browser will most likely display "image error, cannot be viewed", at least firefox does.

You need to set the correct image type (text/html) manually in this case.
up
3
ernest at vogelsinger dot at
19 years ago
When you rely on URL rewriting to pass the PHP session ID you should be careful with ob_get_contents(), as this might disable URL rewriting completely.

Example:
ob_start();
session_start();
echo '<a href=".">self link</a>';
$data = ob_get_contents();
ob_end_clean();
echo $data;

In the example above, URL rewriting will never occur. In fact, rewriting would occur if you ended the buffering envelope using ob_end_flush(). It seems to me that rewriting occurs in the very same buffering envelope where the session gets started, not at the final output stage.

If you need a scenario like the one above, using an "inner envelope" will help:

ob_start();
ob_start(); // add the inner buffering envelope
session_start();
echo '<a href=".">self link</a>';
ob_end_flush(); // closing the inner envelope will activate URL rewriting
$data = ob_get_contents();
ob_end_clean();
echo $data;

In case you're interested or believe like me that this is rather a design flaw instead of a feature, please visit bug #35933 (http://bugs.php.net/bug.php?id=35933) and comment on it.
To Top