PHP Doku:: Gibt eine Meldung aus und beendet das aktuelle Skript - function.exit.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzSonstige GrunderweiterungenMiscellaneous FunctionsSonstige Funktionenexit

Ein Service von Reinhard Neidl - Webprogrammierung.

Sonstige Funktionen




(PHP 4, PHP 5)

exitGibt eine Meldung aus und beendet das aktuelle Skript


void exit ([ string $status ] )
void exit ( int $status )

Beendet die Ausführung des Skripts.



Falls status eine Zeichenkette ist, gibt diese Funktion beim Beenden den status aus.

Falls status eine Ganzzahl ist, wird dieser Wert als Exit-Status verwendet. Ein Exit-Status sollte im Bereich von 0 bis 254 liegen, weil der Exit-Status 255 von PHP reserviert ist und deshalb nicht benutzt werden sollte. Der Status 0 wird verwendet, um ein Programm erfolgreich zu beenden.

Hinweis: Falls status eine Ganzzahl ist, wird er von PHP >= 4.2.0 NICHT ausgegeben.


Es wird kein Wert zurückgegeben.


Beispiel #1 exit()-Beispiel


$datei fopen($dateiname'r')
    or exit(
"kann Datei $dateiname nicht öffnen");


Beispiel #2 exit()-Status-Beispiel


// das Programm normal beenden

// das Programm mit einem Fehlercode beenden
0376); // oktal



Hinweis: Da dies ein Sprachkonstrukt und keine Funktion ist, können Sie dieses nicht mit Variablenfunktionen verwenden.


Dieses Sprachkonstrukt entspricht die().

Siehe auch

16 BenutzerBeiträge:
- Beiträge aktualisieren...
nicoladinh at gmail dot com
2.12.2010 9:09
Calling to exit() will flush all buffers started by ob_start() to default output.
dexen dot devries at gmail dot com
3.11.2010 14:54
If you want to avoid calling exit() in FastCGI as per the comments below, but really, positively want to exit cleanly from nested function call or include, consider doing it the Python way:

define an exception named `SystemExit', throw it instead of calling exit() and catch it in index.php with an empty handler to finish script execution cleanly.


// file: index.php
class SystemExit extends Exception {}
try {
/* code code */
catch (
SystemExit $e) { /* do nothing */ }
// end of file: index.php

// some deeply nested function or .php file   

   throw new
SystemExit(); // instead of exit()

vincent dot laag at gmail dot com
24.09.2010 21:51
Don't use the  exit() function in the auto prepend file with fastcgi (linux/bsd os).
It has the effect of leaving opened files with for result at least a nice  "Too many open files  ..." error.
matt at serverboy dot net
23.03.2010 21:11
It should be noted that if building a site that runs on FastCGI, calling exit will generate an error in the server's log file. This can quickly fill up.

Also, using exit will diminish the performance benefit gained on FastCGI setups. Instead, consider using code like this:


if( /* error case */ )
"Invalid request";
else {
/* The rest of your application */

I've also seen developers get around this issue with FastCGI by wrapping their code in a switch statement and using breaks:


switch(true) {



if($x > $y) {
"Sorry, that didn't work.";

// ...


It does carry some overhead, but compared to the alternative, it does the job well.
albert at removethis dot peschar dot net
5.05.2009 20:50
jbezorg at gmail proposed the following:


header('Location: /');


After sending the `Location:' header PHP _will_ continue parsing, and all code below the header() call will still be executed.  So instead use:


header('Location: /');

jbezNULLorg at gmNULLail dot com
24.02.2009 21:26
If you are retroactively going through included files to prevent them from being accessed, you can use the following.

header('location: /'); // or exit();

// rest of code

void a t informance d o t info
26.10.2008 23:11
To rich dot lovely at klikzltd dot co dot uk:

Using a "@" before header() to suppress its error, and relying on the "headers already sent" error seems to me a very bad idea while building any serious website.

This is *not* a clean way to prevent a file from being called directly. At least this is not a secure method, as you rely on the presence of an exception sent by the parser at runtime.

I recommend using a more common way as defining a constant or assigning a variable with any value, and checking for its presence in the included script, like:

in index.php:
('INDEX', true);

in your included file:
if (!defined('INDEX')) {
'You cannot call this script directly !');


rich dot lovely at klikzltd dot co dot uk
19.07.2008 15:24
usefull feature:

@header("location: path/to/home/page") and exit();


We have a "modular" website, with common header and footer files, and different content modules, eg photos, usually accessed via index.php?p=photos

<?php include "head.php";
$_GET['p'] . ".php"//Change this - SECURITY!
include "foot.php";

@header("location: index.php?p=photos") and exit();

//Code to display photos etc

If someone tries to access photos.php, which doesn't produce a full html page by definition, the header directive sends them to the full version, returns true, and therefore runs the exit() function.

If they go in normally, the header function should die with the "headers already sent" error, which is supressed by the @ and returns false, preventing the exit statement from running due to lazy execution.
12.07.2007 0:11
In relation to the below comment, you may find that using the following may be more appropriate:

# ... user has pressed log out, cookies have been wiped, etc.

// Stay on the same page at time of logout (useful if a page is also available to anyone who isn't logged in
header ("Location: http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);


Of course $_SERVER['PHP_SELF'] can be omitted if you wish to redirect to the root directory of the site ( or a path of your choosing can be used instead.

Alternatively, if you've a solid system implemented and logged out users can access the page too, you can continue with showing the page without using exit() or header().
Roumen Semov
16.02.2006 20: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.
nospam at mydomain dot com
27.09.2004 11: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.08.2003 17: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.02.2003 21: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
9.08.2002 13: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
14.07.2002 5: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.
devinemke at devinemke dot com
11.01.2002 9: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');
blah blah blah
include ('footer.php');

PHP Powered Diese Seite bei
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)