exit

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

exit输出一个消息并且退出当前脚本

说明

exit ( string $status = ? ) : void
exit ( int $status ) : void

中止脚本的执行。 尽管调用了 exit()Shutdown函数 以及 object destructors 总是会被执行。

exit 是个语法结构,如果没有 status 参数要传入,可以省略圆括号。

参数

status

如果 status 是一个字符串,在退出之前该函数会打印 status

如果 status 是一个 int,该值会作为退出状态码,并且不会被打印输出。 退出状态码应该在范围0至254,不应使用被PHP保留的退出状态码255。 状态码0用于成功中止程序。

返回值

没有返回值。

范例

Example #1 exit() 例子

<?php

$filename 
'/path/to/data-file';
$file fopen($filename'r')
    or exit(
"unable to open file ($filename)");

?>

Example #2 exit() 状态码例子

<?php

//exit program normally
exit;
exit();
exit(
0);

//exit with an error code
exit(1);
exit(
0376); //octal

?>

Example #3 无论如何,Shutdown函数与析构函数都会被执行

<?php
class Foo
{
    public function 
__destruct()
    {
        echo 
'Destruct: ' __METHOD__ '()' PHP_EOL;
    }
}

function 
shutdown()
{
    echo 
'Shutdown: ' __FUNCTION__ '()' PHP_EOL;
}

$foo = new Foo();
register_shutdown_function('shutdown');

exit();
echo 
'This will not be output.';
?>

以上例程会输出:

 Shutdown: shutdown()
 Destruct: Foo::__destruct()
 

注释

Note: 因为是一个语言构造器而不是一个函数,不能被 可变函数 调用。

Note:

该语法结构等同于 die()

参见

User Contributed Notes

bill dot gates at hotmail dot com 16-Jun-2021 01:43
Be noticed about uopz (User Operations for Zend) extension of PHP. It disables (prevents) halting of PHP scripts (both FPM and CLI) on calling `exit()` and `die()` by default just after enabling the extension. Therefore your script will continue to execute.

Details: https://www.php.net/manual/en/uopz.configuration.php#ini.uopz.exit
Alexander Behling 26-Feb-2021 11:33
it is also possible to include function calls e.g. logging function to write the error in a log file.

e.g.

function logerror($error){
file_put_contents(__DIR__.'/error_log', 'Error occured: '.$error');
}

die(logerror('error msg here');

This will terminate the script and write "error msg here" to error.log

You could use this for example when query the database to log when the query fails.
jean dot claveau at gmail dot com 25-Jan-2020 10:56
Beware if you enabled uopz extension, it disables exit / die() by default. They are just "skipped".

https://www.php.net/manual/en/function.uopz-allow-exit.php
powtac at gmx de 04-Jul-2018 09:25
When a object is passed as $status and it consists of a __toString() magic method the string value of this method will be used as $status. If the object does not contain a __toString method, exit will throw a catchable fatal error.
chris at ocproducts dot com 01-Mar-2018 10:57
Calling 'exit' will bypass the auto_append_file option.
On some free hosting this risks you getting removed, as they may be using for ads and analytics.

So be a bit careful if using this on the most common output branch.
marco dot marsala at live dot it 14-Feb-2018 09:16
Please note $status is printed to stdout, not stderr.
sunfundev at gmail dot com 07-Sep-2017 04:02
>> Shutdown functions and object destructors will always be executed even if exit is called.

It is false if you call exit into desctructor.

Normal exit:
<?php
class A
{
    public function
__destruct()
    {
        echo
"bye A\n";
    }
}

class
B
{
    public function
__destruct()
    {
        echo
"bye B\n";
    }
}

$a = new A;
$b = new B;
exit;

// Output:
// bye B
// bye A
?>

// Exit into desctructor:
<?php
class A
{
    public function
__destruct()
    {
        echo
"bye A\n";
    }
}

class
B
{
    public function
__destruct()
    {
        echo
"bye B\n";
        exit;
    }
}

$a = new A;
$b = new B;

// Output:
// bye B
?>
kehaovista at qq dot com 22-Jan-2016 01:20
<?php

class Foo
{
    public function
__construct()
    {
       
register_shutdown_function([$this, 'shutdown']);
    }

    public function
__destruct()
    {
        echo
'Destruct: ' . __METHOD__ . '()' . PHP_EOL;
    }

    function
shutdown()
    {
        echo
'Shutdown: ' . __FUNCTION__ . '()' . PHP_EOL;
    }
}

$foo = new Foo();
exit();

// output is
//Shutdown: shutdown()
//Destruct: Foo::__destruct()
m dot libergolis at gmail dot com 18-Aug-2015 06:44
In addition to "void a t informance d o t info", here's a one-liner that requires no constant:

<?php basename($_SERVER['PHP_SELF']) == basename(__FILE__) && die('Thou shall not pass!'); ?>

Placing it at the beginning of a PHP file will prevent direct access to the script.

To redirect to / instead of dying:

<?php
if (basename($_SERVER['PHP_SELF']) == basename(__FILE__)) {
    if (
ob_get_contents()) ob_clean(); // ob_get_contents() even works without active output buffering
   
header('Location: /');
    die;
}
?>

Doing the same in a one-liner:

<?php basename($_SERVER['PHP_SELF']) == basename(__FILE__) && (!ob_get_contents() || ob_clean()) && header('Location: /') && die; ?>

A note to security: Even though $_SERVER['PHP_SELF'] comes from the user, it's safe to assume its validity, as the "manipulation" takes place _before_ the actual file execution, meaning that the string _must_ have been valid enough to execute the file. Also, basename() is binary safe, so you can safely rely on this function.
theonenkl at gmail dot com 21-Apr-2015 03:33
A side-note for the use of exit with finally: if you exit somewhere in a try block, the finally won't be executed. Could not sound obvious: for instance in Java you never issue an exit, at least a return in your controller; in PHP instead you could find yourself exiting from a controller method (e.g. in case you issue a redirect).

Here follows the POC:

<?php
echo "testing finally wit exit\n";

try {
    echo
"In try, exiting\n";

    exit;
} catch(
Exception $e) {
    echo
"catched\n";
} finally {
    echo
"in finally\n";
}

echo
"In the end\n";
?>

This will print:

testing finally wit exit
In try, exiting
alexyam at live dot com 09-Apr-2012 04:19
When using php-fpm, fastcgi_finish_request() should be used instead of register_shutdown_function() and exit()

For example, under nginx and php-fpm 5.3+, this will make browsers wait 10 seconds to show output:

<?php
   
echo "You have to wait 10 seconds to see this.<br>";
   
register_shutdown_function('shutdown');
    exit;
    function
shutdown(){
       
sleep(10);
        echo
"Because exit() doesn't terminate php-fpm calls immediately.<br>";
    }
?>

This doesn't:

<?php
   
echo "You can see this from the browser immediately.<br>";
   
fastcgi_finish_request();
   
sleep(10);
    echo
"You can't see this form the browser.";
?>
nicoladinh at gmail dot com 02-Dec-2010 12:09
Calling to exit() will flush all buffers started by ob_start() to default output.
dexen dot devries at gmail dot com 03-Nov-2010 05: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.

<?php

// 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   

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

?>
vincent dot laag at gmail dot com 24-Sep-2010 12: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-Mar-2010 12: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:

<?php

if( /* error case */ )
    echo
"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:

index.php:
<?php

switch(true) {
    case
true:
        require(
'application.php');
}

?>

application.php:
<?php

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

// ...

?>

It does carry some overhead, but compared to the alternative, it does the job well.
albert at removethis dot peschar dot net 05-May-2009 11:50
jbezorg at gmail proposed the following:

<?php

if($_SERVER['SCRIPT_FILENAME'] == __FILE__ )
 
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:

<?php

if($_SERVER['SCRIPT_FILENAME'] == __FILE__)
{
 
header('Location: /');
  exit;
}

?>
void a t informance d o t info 26-Oct-2008 02: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:
<?php
define
('INDEX', true);
?>

in your included file:
<?php
if (!defined('INDEX')) {
   die(
'You cannot call this script directly !');
}
?>

BR.

Ninj
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.
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.
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');