|
|
 |
CVI. Funciones de Control de Salida
Las funciones de Control de Salida le permiten controlar
cuándo es enviada la salida desde el script. Esto puede
resultar útil en muchas situaciones diferentes,
especialmente si necesita enviar cabeceras al navegador
después de que su script ha comenzado a enviar datos. Las
funciones de Control de Salida no afectan las cabeceras enviadas
usando header() o
setcookie(), sólo funciones como
echo() y los datos entre bloques de
código PHP.
No se necesitan bibliotecas externas
para construir esta extensión No se necesita ninguna instalación
para usar estas funciones, son parte del núcleo de
PHP. El comportamiento de estas
funciones está afectado por los valores definidos en
php.ini.
Tabla 1. Opciones de configuración del Control de Salida | Nombre | Predeterminado | Modificable | Cambios |
|---|
| output_buffering | "0" | PHP_INI_PERDIR | | | output_handler | NULL | PHP_INI_PERDIR | Disponible desde PHP 4.0.4. | | implicit_flush | "0" | PHP_INI_ALL | PHP_INI_PERDIR en PHP <= 4.2.3. |
For further details and definitions of the
PHP_INI_* constants, see the Apéndice G.
A continuación se
presenta una corta explicación de las directivas de
configuración.
- output_buffering
boolean/integer
Puede habilitar el uso de búferes de salida para todos los
archivos, definiendo esta directiva como 'On'. Si desea limitar
el tamaño del búfer a cierta cantidad - puede usar
un número máximo de bytes, en lugar de 'On', como
valor para esta directiva (p.ej., output_buffering=4096). A
partir de PHP 4.3.5, esta directiva siempre tiene el valor Off en
PHP-CLI.
- output_handler
string
Puede redireccionar toda la salida de sus scripts a una
función. Por ejemplo, si establece el valor de
output_handler a mb_output_handler(), la
codificación de caracteres será convertida de forma
transparente a la codificación especificada. Al definir
cualquier gestor de salida, el control mediante búferes se
activa automáticamente.
Nota:
Solo funciones integradas del lenguaje pueden ser usadas con
esta directiva. Para funciones definidas por el usuario, use
ob_start().
- implicit_flush
boolean
FALSE por defecto. Cambiar este valor a TRUE le indica a PHP
que debe decirle a la capa de salida que se vacÃe
automáticamente después de cada bloque de
salida. Esto es equivalente a llamar la función de PHP
flush() después de todas y cada una de
las llamadas a print() o
echo(), y cada bloque HTML.
Cuando use PHP bajo un entorno web, el habilitar esta
opción tiene unas implicaciones serias en el rendimiento,
y por lo general se recomienda su uso únicamente para
propósitos de depuración. Este valor es igual a
TRUE por defecto cuando se opera bajo la SAPI
CLI.
Vea también ob_implicit_flush().
Esta extensión no tiene
ningún tipo de recurso definido. Esta extensión no tiene ninguna
constante definida.
Ejemplo 1. Ejemplo de Control de Salida |
<?php
ob_start();
echo "Hola\n";
setcookie("nombre_cookie", "datos_cookie");
ob_end_flush();
?>
|
|
En el anterior ejemplo, la salida de echo()
serÃa almacenada en el búfer de salida hasta que
ob_end_flush() sea llamada. Entre tanto, la
llamada a setcookie() almacena
satisfactoriamente una cookie sin causar un error. (Normalmente,
usted no puede enviar cabeceras al navegador después de
que se han enviado datos.)
Nota:
Cuando se actualice desde PHP 4.1 (y 4.2) hacia 4.3, debe
asegurarse de que implict_flush tenga el
valor OFF en su php.ini debido a un fallo
en versiones antiguas, de otra forma, cualquier salida procesada
por ob_start() no será ocultada en la
salida final.
- Tabla de contenidos
- flush -- Vaciar el búfer de salida
- ob_clean --
Limpiar (eliminar) el búfer de salida
- ob_end_clean --
Limpiar (eliminar) y deshabilitar los búferes de salida
- ob_end_flush --
Volcar (enviar) el búfer de salida y deshabilitar el uso
del búfer
- ob_flush --
Vaciar (enviar) el búfer de salida
- ob_get_clean --
Obtener los contenidos del búfer actual y eliminar el
búfer de salida actual
- ob_get_contents --
Devolver el contenido del búfer de salida
- ob_get_flush --
Volcar el búfer de salida, devolverlo como una cadena y
deshabilitar el uso de búferes de salida
- ob_get_length --
Devolver la longitud del búfer de salida
- ob_get_level --
Devolver el nivel de anidamiento del mecanismo de búferes
de salida
- ob_get_status --
Obtener el status de los búferes de salida
- ob_gzhandler --
Llamada de retorno de ob_start para comprimir mediante gzip el
búfer de salida
- ob_implicit_flush --
Habilitar/deshabilitar el volcado implÃcito
- ob_list_handlers --
Listar todos los gestores de salida en uso
- ob_start -- Habilitar el uso de búferes de
salida
- output_add_rewrite_var --
Agregar valores de re-escritura de URL
- output_reset_rewrite_vars --
Reestablecer los valores del mecanismo de re-escritura de URLs
add a note
User Contributed Notes
Funciones de Control de Salida
kamermans at teratechnologies dot net
21-Aug-2006 01:30
Output buffering is set to '4096' instead of 'Off' or '0' by default in the php-5.0.4-10.5 RPM for Fedora Core release 4 (Stentz). This has cost me much time!
webmaster [at] oltec-solutions [dot] nl
10-Jul-2006 06:00
In re to erwinX at darwineX dot nl:
Adding an ampersand (&) before the hash seems to work too (for me at least), i.e.: http://somedomain.tld/blah.php?arg=x&#something
I guess php then interperts it as an argument to the script. Might save some time and resources.
erwinX at darwineX dot nl
11-Nov-2005 05:35
[Concerns IE refusing to jump to a #something in the URL.]
I encoutered a bug in IE6/W2000 that can be solved by turning output buffering on.
Maybe it also helps in other situations/M$-OS, not sure.
Situation:
A page with a hash in the URL, and IE doesn't jump to that location.
Example:
http://www.bla.com/test.php#something
- In test.php the anchortag is placed normally like:
<a name="something"><br></a>
- test.php takes a few seconds to load because of heavy-duty database activity.
IE just ignores the hash #something.
It looks like IE 'forgets' the hash if it hasn't encoutered it YET in the HTML.
Turning output buffering on resolves that issue.
kend52 at verizon dot net
23-Jun-2005 11:25
I ran out of memory, while output buffering and drawing text on imported images. Only the top portion of the 5MP image was displayed by the browser. Try increasing the memory limit in either the php.ini file( memory_limit = 16M; ) or in the .htaccess file( php_value memory_limit "16M" ). Also see function memory_get_usage() .
gruik at libertysurf dot fr
10-Jul-2004 05:53
For those who are looking for optimization, try using buffered output.
I noticed that an output function call (i.e echo()) is somehow time expensive. When using buffered output, only one output function call is made and it seems to be much faster.
Try this :
<?php
your_benchmark_start_function();
for ($i = 0; $i < 5000; $i++)
echo str_repeat ("your string blablabla bla bla", (rand() % 4) + 1)."<br>\n";
echo your_benchmark_end_function();
?>
And then :
<?php
your_benchmark_start_function();
ob_start ();
for ($i = 0; $i < 5000; $i++)
echo str_repeat ("your string blablabla bla bla", (rand() % 4) + 1)."<br>\n";
echo your_benchmark_end_function();
ob_end_flush ();
?>
nobbie @t php d0t net
01-Apr-2004 04:49
There is a problem in MSIE 5.5,6 with regards to Page compression. Users might experience pages not loading completely, or just a blank page.
This articles you are looking for is what you're looking for:
Microsoft Knowledge Base Article - 312496 (for MSIE 6)
Microsoft Knowledge Base Article - 313712 (for MSIE 5.5)
It states that you should upgrade to the latest MSIE Service Pack to fix the following problem:
Internet Explorer May Lose the First 2,048 Bytes of Data That Are Sent Back from a Web Server That Uses HTTP Compression
tijmen
09-Jul-2003 04:44
Trying to benchmark your server when using output_buffering ?
Don't forget that the value 4096 in the php.ini will give you complete different loadtimes compares to the value of 1.
In the first case the output will be sent after buffering 4096 and the loadtime timed at the end of the page will contain the loadtime needed to download the complete page in the clientbrowser while the second value will contain the loadtime needed to place the complete page in the buffer. The time needed for sending is not clocked.
This can be very frustrating if you don't see the differance between server and the 1st is using 4096 instead of 1.
Although technically much faster than the second server the second server was providing much better loadtime results.
This result will grow when using large amounts of output.
But this becomes interesting if you want to measure the time needed for the page to be loaded for the client.
| |
|
| Chiste de... Niños | | Dos puntos de vista | - ¿Tú sabías que todas las personas tienen un pie más pequeño que el otro?
- Pues yo debo ser especial, porque lo que tengo es uno más grande que el otro. | | Chistes en tu mail | | ©ContenidosGratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|