exit

(PHP 4, PHP 5, PHP 7)

exitВыводит сообщение и прекращает выполнение текущего скрипта

Описание

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

Прекращает выполнение скрипта. Функции отключения и деструкторы объекта будут запущены даже если была вызвана конструкция exit.

exit - это конструкция языка, и она может быть вызвана без круглых скобок если не передается параметр status.

Список параметров

status

Если параметр status задан в виде строки, то эта функция выведет содержимое status перед выходом.

Если параметр status задан в виде целого числа (integer), то это значение будет использовано как статус выхода и не будет выведено. Статусы выхода должны быть в диапазоне от 0 до 254, статус выхода 255 зарезервирован PHP и не должен использоваться. Статус выхода 0 используется для успешного завершения программы.

Замечание: PHP >= 4.2.0 НЕ выведет параметр status если он задан как целое число (integer).

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример использования exit

<?php

$filename 
'/path/to/data-file';
$file fopen($filename'r')
    or exit(
"Невозможно открыть файл ($filename)");

?>

Пример #2 Пример использования exit со статусом выхода

<?php

//нормальный выход из программы
exit;
exit();
exit(
0);

//выход с кодом ошибки
exit(1);
exit(
0376); //восьмеричный

?>

Пример #3 Функции выключения и деструкторы выполняются независимо

<?php
class Foo
{
    public function 
__destruct()
    {
        echo 
'Деинициализировать: ' __METHOD__ '()' PHP_EOL;
    }
}

function 
shutdown()
{
    echo 
'Завершить: ' __FUNCTION__ '()' PHP_EOL;
}

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

exit();
echo 
'Эта строка не будет выведена.';
?>

Результат выполнения данного примера:

 Завершить: shutdown()
 Деинициализировать: Foo::__destruct()
 

Примечания

Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.

Замечание:

Эта языковая конструкция эквивалентна функции die().

Смотрите также

  • register_shutdown_function() - Регистрирует функцию, которая выполнится по завершении работы скрипта

Коментарии

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');
2002-01-11 02:38:15
http://php5.kiev.ua/manual/ru/function.exit.html
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.
2003-08-23 11:14:28
http://php5.kiev.ua/manual/ru/function.exit.html
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
2008-10-26 16:11:00
http://php5.kiev.ua/manual/ru/function.exit.html
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;
}

?>
2009-05-05 14:50:27
http://php5.kiev.ua/manual/ru/function.exit.html
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.
2010-09-24 15:51:31
http://php5.kiev.ua/manual/ru/function.exit.html
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()

?>
2010-11-03 07:54:16
http://php5.kiev.ua/manual/ru/function.exit.html
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.";
?>
2012-04-09 19:19:10
http://php5.kiev.ua/manual/ru/function.exit.html
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
2015-04-21 18:33:37
http://php5.kiev.ua/manual/ru/function.exit.html
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.
2015-08-18 09:44:12
http://php5.kiev.ua/manual/ru/function.exit.html
>> 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
?>
2017-09-07 19:02:21
http://php5.kiev.ua/manual/ru/function.exit.html
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.
2018-03-02 00:57:53
http://php5.kiev.ua/manual/ru/function.exit.html
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
2020-01-26 00:56:33
http://php5.kiev.ua/manual/ru/function.exit.html
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
2021-06-16 16:43:47
http://php5.kiev.ua/manual/ru/function.exit.html
These are the standard error codes in Linux or UNIX.

1 - Catchall for general errors
2 - Misuse of shell builtins (according to Bash documentation)
126 - Command invoked cannot execute
127 - “command not found”
128 - Invalid argument to exit
128+n - Fatal error signal “n”
130 - Script terminated by Control-C
255\* - Exit status out of range
2022-11-17 12:59:58
http://php5.kiev.ua/manual/ru/function.exit.html

    Поддержать сайт на родительском проекте КГБ