|
|
 |
exit (PHP 3, PHP 4, PHP 5) exit -- Imprime un mensaje y termina el script
actual Descripciónvoid exit ( [string status] ) void exit ( int status ) Nota:
Esta no es una función real, es una construcción
del lenguaje.
Nota:
PHP >= 4.2.0 NO imprime el status si
es un valor integer.
La función exit() finaliza la
ejecución del script. Imprime
status justo antes de salir.
Si status es un valor
integer, ese valor será usado también
como el status de salida. Los status de salida deben estar en el
rango 0 a 254, el status de salida 255 es reservado por PHP y no
debe ser usado. El status 0 es usado para finalizar el programa
de forma satisfactoria.
Ejemplo 1. Ejemplo de exit() |
<?php
$nombre_archivo = '/ruta/hacia/archivo-datos';
$archivo = fopen($nombre_archivo, 'r')
or exit("no se pudo abrir el archivo ($nombre_archivo)");
?>
|
|
Ejemplo 2. Ejemplo de status de exit() |
<?php
exit;
exit();
exit(0);
exit(1);
exit(0376); ?>
|
|
Nota:
La función die() es un alias para
exit().
Vea también:
register_shutdown_function().
Roumen Semov
16-Feb-2006 11:54
Please note in PHP "exit(0)" or simply "exit" returns true.
Any other value but zero will return false. This is good to know in case you are writing command-line php scripts where you need the result of the php script to determine if the next script will run. Example:
shell> ./my_php_script && echo "It ran successfully!"
If you know my_php_script can break somewhere you could do a conditional with an "exit(-1)" and then if the script breaks the command after the && will not execute.
09-Feb-2006 05:26
The note above is irrelevant, because a simple "return" would abort the template included by include or include_once!
francois at bonzon dot com
24-May-2005 06:42
With output buffering on, when sending headers that shouldn't have any data after them, be sure to erase the buffer before exit()ing the script! Like this:
<?php
ob_clean();
exit();
?>
If you don't erase the buffer, in case it was not empty, after sending the headers PHP will still send the buffer content to the browser.
I had Firefox show strange behavior with some of my pages, that it took me quite some time to debug. It was simply because my script was returning 304 Not Modified headers along with the start of an HTML page.
chris at artimador dot com
25-Nov-2004 11:01
When using php as a SHELL scripting language, use die() instead of exit(). If using exit in php5, the script will continue to processes conditionals and other shell_exec functions after the die command.
nospam at mydomain dot com
27-Sep-2004 02:12
Using return instead of exit is to prefer when you want the script that you have included inside another script to die but continue to execute the main script.
// Radcliff
emils at tvnet dot lv
23-Aug-2003 08:14
Note, that using exit() will explicitly cause Roxen webserver to die, if PHP is used as Roxen SAPI module. There is no known workaround for that, except not to use exit(). CGI versions of PHP are not affected.
mbostrom at paragee dot com
26-Feb-2003 12:45
In PHP 4.3.1 (and possibly 4.3.0), running scripts from the command line works a lot better. This is probably because 4.3.x has a whole new CLI mode.
Specifically, exit status is now returned (to the shell) as you would expect. This is a godsend for writing embedded email processing scripts, as much email infrastructure (fetchmail, qmail, mutt, etc.) is dependant upon correctly returned status codes, and the inability to return a status code (as in PHP 4.2.x) is an insurmountable obstacle.
$_SERVER["argv"] is also always available in 4.3.x, I think, whereas in 4.2.x php.ini could prevent it from being available.
(On the downside, I had to ./configure --without-mysql in order to get 4.3.1 to compile on RedHat 8.0. Otherwise there was what looked like a fatal compile warning (that I might also have been able to ignore somehow).
The "fatal warning" FYI:
ext/mysql/libmysql/my_tempnam.o: In function `my_tempnam':
ext/mysql/libmysql/my_tempnam.c:103: the use of `tempnam' is dangerous, better use `mkstemp'
Changing the code from tempnam to mkstemp would probably not be overly complicated, but it is non-trivial.)
shaun at NOshatSPAM dot net
09-Aug-2002 04:13
return may be preferable to exit in certain situations, especially when dealing with the PHP binary and the shell.
I have a script which is the recipient of a mail alias, i.e. mail sent to that alias is piped to the script instead of being delivered to a mailbox. Using exit in this script resulted in the sender of the email getting a delivery failure notice. This was not the desired behavior, I wanted to silently discard messages which did not satisfy the script's requirements.
After several hours of trying to figure out what integer value I should pass to exit() to satisfy sendmail, I tried using return instead of exit. Worked like a charm. Sendmail didn't like exit but it was perfectly happy with return. So, if you're running into trouble with exit and other system binaries, try using return instead.
iamfast at tampabay dot rr dot com
13-Jul-2002 08:12
If you are working with images or something of the sort that is not html, and use auto appending, call exit before you close your php tag, so that the footer is not included, corrupting the end of the file.
--Nate
devinemke at devinemke dot com
11-Jan-2002 12:38
If you are using templates with numerous includes then exit() will end you script and your template will not complete (no </table>, </body>, </html> etc...). Rather than having complex nested conditional logic within your content, just create a "footer.php" file that closes all of your HTML and if you want to exit out of a script just include() the footer before you exit().
for example:
include ('header.php');
blah blah blah
if (!$mysql_connect) {
echo "unable to connect";
include ('footer.php');
exit;
}
blah blah blah
include ('footer.php');
| |
| | Citas célebres | Decir que podrás amar a una persona toda la vida es como pretender que una vela continúe encendida durante todo el tiempo que te quede de vida. Leon Tolstoi Escritor ruso (1828-1910) | | Citas en tu mail | | ©Contenidos Gratis |
| Chiste de... Abogados | | Parecidos razonables | Pregunta: ¿Cuál es la diferencia entre un abogado y un vampiro?
Respuesta: ... el vampiro te chupa la sangre sólo de noche. | | 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. |
|
|