|
|
 |
CapÃtulo 40. Manejando conexionesNota: Todo lo siguiente se aplica a partir de la versión 3.0.7 y posterior.
Internamente en PHP se mantiene el estado de la conexión. Hay 3 posibles
estados:
Cuando un script PHP se está ejecutando se activa el estado NORMAL.
Si el cliente remoto se desconecta, se pasa al estado ABORTED. Esto
suele ocurrir cuando el usuario pulsa en el botón STOP del navegador.
Si se alcanza el lÃmite de tiempo impuesto por PHP (ver
set_time_limit()), se pasa al estado TIMEOUT.
Puedes decidir si quieres que la desconexión de un cliente cause que tu
script sea abortado. Algunas veces es cómodo que tus scripts se ejecuten
por completo, incluso si no existe ya un navegador remoto que reciba la
salida. El comportamiento por defecto es sin embargo, que tu script se
aborte cuando el cliente remoto se desconecta. Este comportamiento puede
ser configurado vÃa la directiva ignore_user_abort en el fichero php3.ini,
o también con la función ignore_user_abort(). Si no le
espeficicas al PHP que cuando un usuario aborte lo ignore, tu script terminará
su ejecución. La única excepción es si tienes registrada un función de
desconexión usando la función register_shutdown_function().
Con una función de desconexión, cuando un usuario remoto pulsa en el botón
STOP, la próxima vez que tu script intenta mostrar algo, PHP detecta que
la conexión ha sido abortada y se llama a la función de desconexión. Esta
función de desconexión también se llama al final de la ejecución de tu
script cuando se ha ejecutado normalmente, de manera que si quieres hacer
algo diferente en caso de que un cliente se haya desconectado, puedes usar
la función connection_aborted(). Esta función devuelve
TRUE si la conexión fue abortada.
Vuestro script también se puede terminar por un temporizador interno.
El timeout por defecto es de 30 segundos. Se puede cambiar usando
la directiva max_execution_time en el fichero php.ini o la correspondiente
directiva php_max_execution_time en la configuración del servidor de páginas
Apache, como también con la función set_time_limit(). Cuando
el temporizador expira, el script se aborta como en el caso de la desconexión
del cliente, de manera que si se ha definido una función de desconexión,
esta se llamará. Dentro de esta función de desconexión, puedes comprobar
si fue el timeout el que causó que se llamara a la función de desconexión,
llamando a la función connection_timeout(). Esta función
devolverá verdadero si el timeout causa que se llame a la función de
desconexión.
Hay que destacar que ambos, el estado ABORTED y el TIMEOUT, se pueden
activar al mismo tiempo. Esto es posible si le dices a PHP que ignore
las desconexiones intencionadas de los usuarios. PHP aún notará el hecho
de que el usuario puede haberse desconectado, pero el script continuará
ejecutándose. Si se alcanza el tiempo lÃmite de ejecución será abortado
y, si se ha definido una función de desconexión, esta será llamada. En
este punto, encontrarás que las funciones connection_timeout()
y connection_aborted() devuelven verdadero. Puedes
comprobar ambos estados de una manera simple usando la función
connection_status(). Esta función devuelve un campo de bit de los
estados activos. De este modo, si ambos estados están activos devolverÃa
por ejemplo un valor 3.
add a note
User Contributed Notes
Manejando conexiones
bg at ms dot com
22-Sep-2005 06:42
Confirmed. User presses STOP button. This sends a RST packet and closes the connection. PHP is most certainly immediately affected (i.e., the script is stopped, whether or not any output is pending for the user, or even if script is just grinding away on a database without having output anything).
ignore_user_abort() exists to prevent this.
If user STOPS, script ignores the RST and runs to completion (the output is apparently ignored by apache and not sent to the user, who sent the RST and closed the TCP connection). If user's connection just vanishes (isp problem, disconnect, whatever), and there is no RST sent by user, then eventually the script will timeout.
hrgan at melibado dot com
12-Dec-2004 11:08
As it was said, connection handling is very useful when web application need to do something in background. I found it very useful when application need something from database, wrap that data with template, create some html files and save it to filesystem. And all that on server with heavy load. Without connection handling - function ignore_user_abort() - this process can be interrupted by user and final step will never be done.
Lee
18-Sep-2004 03:16
The point mentioned in the last comment isn't always the case.
If a user's connection is lost half way through an order processing script is confirming a user's credit card/adding them to a DB, etc (due to their ISP going down, network trouble... whatever) and your script tries to send back output (such as, "pre-processing order" or any other type of confirmation), then your script will abort -- and this could cause problems for your process.
I have an order script that adds data to a InnoDB database (through MySQL) and only commits the transactions upon successful completion. Without ignore_user_abort(), I have had times when a user's connection dropped during the processing phase... and their card was charged, but they weren't added to my local DB.
So, it's always safe to ignore any aborts if you are processing sensitive transactions that should go ahead, whether your user is "watching" on the other end or not.
ej at campbell *dot* name
12-Feb-2004 05:01
I don't think the first example given below will occur in the real world.
As long as your order handling script does not output anything, there's no way that it will be aborted before it completes processing (unless it timeouts). PHP only senses user aborts when a script sends output. If there's no output sent to the client before processing completes, which is presumably the case for an order handling script, the script will run to completion.
So, the only time a script can be terminated due to the user hitting stop is when it sends output. If you don't send any output until processing completes, you don't have to worry about user aborts.
pulstar at mail dot com
06-Aug-2003 11:32
These functions are very useful for example if you need to control when a visitor in your website place an order and you need to check if he/she didn't clicked the submit button twice or cancelled the submit just after have clicked the submit button.
If your visitor click the stop button just after have submitted it, your script may stop in the middle of the process of registering the products and do not finish the list, generating inconsistency in your database.
With the ignore_user_abort() function you can make your script finish everything fine and after you can check with register_shutdown_function() and connection_aborted() if the visitor cancelled the submission or lost his/her connection. If he/she did, you can set the order as not confirmed and when the visitor came back, you can present the old order again.
To prevent a double click of the submit button, you can disable it with javascript or in your script you can set a flag for that order, which will be recorded into the database. Before accept a new submission, the script will check if the same order was not placed before and reject it. This will work fine, as the script have finished the job before.
Note that if you use ob_start("callback_function") in the begin of your script, you can specify a callback function that will act like the shutdown function when our script ends and also will let you to work on the generated page before send it to the visitor.
| |
| | Citas célebres | No estimes el dinero ni en más ni en menos de lo que vale: es un buen servidor y un mal amo. Alejandro Dumas Escritor francés (1802-1870) | | Citas en tu mail | | ©Contenidos Gratis |
| Chiste de... Viejos | | El abuelo | - Nieto nieto, como se llama el capullo alemán ese que me esconde las cosas...
- Alzehimer, abuelo, Alzehimer. | | 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. |
|
|