exit
Прекращает выполнение скрипта. Функции отключения и деструкторы объекта будут запущены, даже если была вызвана конструкция exit .
exit — это конструкция языка, и она может быть вызвана без круглых скобок, если не передаётся параметр status .
Список параметров
Если status задан в виде строки, то эта конструкция выведет содержимое status перед выходом.
Если status задан в виде целого числа ( int ), то это значение будет использовано как статус выхода и не будет выведено. Статусы выхода должны быть в диапазоне от 0 до 254, статус выхода 255 зарезервирован PHP и не должен использоваться. Статус выхода 0 используется для успешного завершения программы.
Возвращаемые значения
Функция не возвращает значения после выполнения.
Примеры
Пример #1 Пример использования exit
$filename = ‘/path/to/data-file’ ;
$file = fopen ( $filename , ‘r’ )
or exit( «Невозможно открыть файл ( $filename )» );
Пример #2 Пример использования exit со статусом выхода
//обычный выход из программы
exit;
exit();
exit( 0 );
//выход с кодом ошибки
exit( 1 );
exit( 0376 ); //восьмеричный
Пример #3 Функции выключения и деструкторы выполняются независимо
class Foo
public function __destruct ()
echo ‘Деинициализировать: ‘ . __METHOD__ . ‘()’ . PHP_EOL ;
>
>
?php
function shutdown ()
echo ‘Завершить: ‘ . __FUNCTION__ . ‘()’ . PHP_EOL ;
>
$foo = new Foo ();
register_shutdown_function ( ‘shutdown’ );
exit();
echo ‘Эта строка не будет выведена.’ ;
?>
Результат выполнения данного примера:
Завершить: shutdown() Деинициализировать: Foo::__destruct()
Примечания
Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций или именованных аргументов.
Замечание:
Эта языковая конструкция эквивалентна конструкции die() .
Смотрите также
- register_shutdown_function() — Регистрирует функцию, которая выполнится при завершении работы скрипта
User Contributed Notes 21 notes
13 years ago
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
if ( SOME_EXIT_CONDITION )
throw new SystemExit (); // instead of exit()
14 years ago
jbezorg at gmail proposed the following:
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:
if( $_SERVER [ ‘SCRIPT_FILENAME’ ] == __FILE__ )
header ( ‘Location: /’ );
exit;
>
8 years ago
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:
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
13 years ago
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.
3 years ago
Beware if you enabled uopz extension, it disables exit / die() by default. They are just «skipped».
2 years ago
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.
15 years ago
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:
define ( ‘INDEX’ , true );
?>
in your included file:
if (! defined ( ‘INDEX’ )) die( ‘You cannot call this script directly !’ );
>
?>
BR.
20 years ago
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.
11 years ago
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:
echo «You have to wait 10 seconds to see this.
» ;
register_shutdown_function ( ‘shutdown’ );
exit;
function shutdown () sleep ( 10 );
echo «Because exit() doesn’t terminate php-fpm calls immediately.
» ;
>
?>
This doesn’t:
echo «You can see this from the browser immediately.
» ;
fastcgi_finish_request ();
sleep ( 10 );
echo «You can’t see this form the browser.» ;
?>
8 years ago
In addition to «void a t informance d o t info», here’s a one-liner that requires no constant:
To redirect to / instead of dying:
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:
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.
21 years ago
include (‘header.php’);
blah blah blah
if (!$mysql_connect) echo «unable to connect»;
include (‘footer.php’);
exit;
>
blah blah blah
include (‘footer.php’);
12 years ago
Calling to exit() will flush all buffers started by ob_start() to default output.
1 year ago
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
5 years ago
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.
6 years ago
>> 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:
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:
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 ;
5 years ago
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.
21 years ago
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.
13 years ago
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 */ )
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:
switch( true ) case true :
require( ‘application.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.
exit, exit(), exit(0), die(), die(0) — How to exit script
I believe that all of these (and even die() or die(0) ) are identical. If they are not identical, which is preferred for exiting a script successfully? If they are identical, is there any preferred standard to indicate successful script completion? I tend to use exit; . EDIT: All of the answers have » die() and exit() are identical» even though I say that in my question. I updated to the title to hopefully make it clearer that this is NOT my question. I want to clearly indicate success from a command line script.
Explosion Pills
asked Nov 7, 2011 at 1:38
Explosion Pills Explosion Pills
189k 54 54 gold badges 330 330 silver badges 408 408 bronze badges
I believe they are identical stackoverflow.com/questions/1795025/…
Nov 7, 2011 at 1:40
don’t use any of these. just use a combination of echo and return.
– user656925
Sep 16, 2012 at 18:07
@HiroProtagonist entirely disagree; return has a different implication
Sep 16, 2012 at 18:16
7 Answers 7
These are all identical. I’m pretty sure die() is just a straight-up alias to exit() , but even if it isn’t, it still acts identically.
When one of these functions is given a string argument, it prints out the string before terminating the process. When it encounters an integer under 255, that integer is considered the return code for the process, which gets passed back to the process which invoked the PHP script. This is particularly useful when writing command line applications (PHP isn’t web-only!).
As far as the difference between exit , exit() , and exit(0) , there really is none. There is definitely no difference between the first two because exit is technically a language construct, not a function, so it can be called with or without parentheses, just like echo . Returning a code of 0 means «this program ran successfully/without errors», and while I don’t know what exactly happens when you don’t pass an argument, PHP.net says that an argument-less exit indicates success, so I would bet it returns 0 , though again PHP.net doesn’t show a default for the argument.
exit(); и return; не останавливают выполнение
Так вот, когда ajax_cmd существует, выполнение продолжается дальше.
Что я неправильно сделал?
Добавлено через 1 минуту
Понятное дело, у меня не столько exit(); и return; в коде.
Это для демонстрации того куда я их ставил.
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
Ответы с готовыми решениями:
замена exit(0) на return
необходимо заменить exit(0) из данного куска кода на return в main, используя при этом.
Return и exit, в чем разница?
Чем отличаются return и exit?

Как завершить выполнение кода (не Exit)?
Ребята помогите с кодом, ниже приведена функция, которая должна проверять значение Edit и в случае.
как после exit возобновить выполнение сценария?
в скрипте использую exit; но прекращает исполняться не только этот скрипт, но и все что следует за.
1178 / 1128 / 94
Регистрация: 31.05.2012
Сообщений: 3,060
Не выполнится дальше код, чудес не бывает.
Если выполняется, значит что то не правильно написано.
Регистрация: 22.02.2012
Сообщений: 327
Такс, придется писать всю чушь которую я придумал.
Вот коротенько, о главном.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
/* Вот здесь мне нужно поставить условие проверки существования ajax-запроса. И если он есть, выполнить необходимое действие, а потом остановить выполнение скрипта. В принципе у меня все работало правильно, до тех пор пока аякс был в другом файле. Но я решил все управление перенести в одно место. Чтобы понятнее было. Даже с тем что написал в первом посте, программа работает. НО в окошечко, в которое должен отображаться только результат работы аякса, кроме него, почему то подгружается вся страничка. Она как бы дублирует себя внутри себя. Понятное дело что я из index.php выполняю index.php, но скрипт то должен остановиться выполнив аякс. */ if (isset($_POST['ajax_cmd'])){ switch($_POST['ajax_cmd']){ case 'cmd1': print_page1(); exit()(или return); break; case 'cmd2': print_page2(); exit()(или return); break; } exit()(или return); } /* * В этом блоке, если есть переменная cmd, выполняется какое либо действие. И потом печатается страница(в следующем блоке). */ if(isset($_GET['cmd']){ switch($_GET['cmd']){ case 'dress': dress(); $page = 'overview'; break; case 'fight': fight(); $page = 'report'; break; case 'buy': create_item(); $page = 'shop'; break; } } /* * В этом блоке исходя из значения переменной печатается та или иная страница. */ switch($_GET['page']){ case 'overview': print_overview_page(); break; case 'messages': print_messages_page(); break; case 'map': print_map_page(); break; }
1178 / 1128 / 94
Регистрация: 31.05.2012
Сообщений: 3,060
1 2 3 4 5 6 7
if (isset($_POST['ajax_cmd'])){ switch($_POST['ajax_cmd']){ case 'cmd1': print_page1(); break; case 'cmd2': print_page2(); break; } exit(); }
Если есть $_POST[‘ajax_cmd’] то по любому данный скрипт перестанет выполняться.
Если конечно это весь код скрипта.
Но есть функции или деструкторы у объектов, который выполнят свой код после exit, так как они выполняются при завершении работы скрипта или уничтожении объектов.
Исключения
В PHP реализована модель исключений, аналогичная тем, что используются в других языках программирования. Исключение в PHP может быть выброшено ( throw ) и поймано ( catch ). Код может быть заключён в блок try , чтобы облегчить обработку потенциальных исключений. У каждого блока try должен быть как минимум один соответствующий блок catch или finally .
Если выброшено исключение, а в текущей области видимости функции нет блока catch , исключение будет «подниматься» по стеку вызовов к вызывающей функции, пока не найдёт подходящий блок catch . Все блоки finally , которые встретятся на этом пути, будут выполнены. Если стек вызовов разворачивается до глобальной области видимости, не встречая подходящего блока catch , программа завершается с неисправимой ошибкой, если не был установлен глобальный обработчик исключений.
Выброшенный объект должен наследовать ( instanceof ) интерфейс Throwable . Попытка выбросить объект, который таковым не является, приведёт к неисправимой ошибке PHP.
Начиная с PHP 8.0.0, ключевое слово throw является выражением и может быть использовано в любом контексте выражения. В предыдущих версиях оно было утверждением и должно было располагаться в отдельной строке.
catch
Блок catch определяет, как реагировать на выброшенное исключение. Блок catch определяет один или несколько типов исключений или ошибок, которые он может обработать, и, по желанию, переменную, которой можно присвоить исключение (указание переменной было обязательно до версии PHP 8.0.0). Первый блок catch , с которым столкнётся выброшенное исключение или ошибка и соответствует типу выброшенного объекта, обработает объект.
Несколько блоков catch могут быть использованы для перехвата различных классов исключений. Нормальное выполнение (когда исключение не выброшено в блоке try ) будет продолжаться после последнего блока catch , определённого в последовательности. Исключения могут быть выброшены ( throw ) (или повторно выброшены) внутри блока catch . В противном случае выполнение будет продолжено после блока catch , который был вызван.
При возникновении исключения, код, следующий за утверждением, не будет выполнен, а PHP попытается найти первый подходящий блок catch . Если исключение не поймано, будет выдана неисправимая ошибка PHP с сообщением » Uncaught Exception . «, если только обработчик не был определён с помощью функции set_exception_handler() .
Начиная с версии PHP 7.1.0, в блоке catch можно указывать несколько исключений, используя символ | . Это полезно, когда разные исключения из разных иерархий классов обрабатываются одинаково.
Начиная с версии PHP 8.0.0, имя переменной для пойманного исключения является необязательным. Если оно не указано, блок catch будет выполнен, но не будет иметь доступа к выброшенному объекту.
finally
Блок finally также может быть указан после или вместо блоков catch . Код в блоке finally всегда будет выполняться после блоков try и catch , независимо от того, было ли выброшено исключение и до возобновления нормального выполнения.
Одно из заметных взаимодействий происходит между блоком finally и оператором return . Если оператор return встречается внутри блоков try или catch , блок finally всё равно будет выполнен. Более того, оператор return выполнится, когда встретится, но результат будет возвращён после выполнения блока finally . Кроме того, если блок finally также содержит оператор return , возвращается значение из блока finally .
Глобальный обработчик исключений
Если исключению разрешено распространяться на глобальную область видимости, оно может быть перехвачено глобальным обработчиком исключений, если он установлен. Функция set_exception_handler() может задать функцию, которая будет вызвана вместо блока catch , если не будет вызван никакой другой блок. Эффект по сути такой же, как если бы вся программа была обёрнута в блок try — catch с этой функцией в качестве catch .
Примечания
Замечание:
Внутренние функции PHP в основном используют отчёт об ошибках, только современные объектно-ориентированные модули используют исключения. Однако ошибки можно легко перевести в исключения с помощью класса ErrorException. Однако эта техника работает только с исправляемыми ошибками.
Пример #1 Преобразование отчётов об ошибках в исключения
function exceptions_error_handler ( $severity , $message , $filename , $lineno ) throw new ErrorException ( $message , 0 , $severity , $filename , $lineno );
>
?php
Подсказка
Примеры
Пример #2 Выбрасывание исключения
function inverse ( $x ) if (! $x ) throw new Exception ( ‘Деление на ноль.’ );
>
return 1 / $x ;
>
?php
try echo inverse ( 5 ) . «\n» ;
echo inverse ( 0 ) . «\n» ;
> catch ( Exception $e ) echo ‘Выброшено исключение: ‘ , $e -> getMessage (), «\n» ;
>
// Продолжение выполнения
echo «Привет, мир\n» ;
?>
Результат выполнения данного примера:
0.2 Выброшено исключение: Деление на ноль. Привет, мир
Пример #3 Обработка исключений с помощью блока finally
function inverse ( $x ) if (! $x ) throw new Exception ( ‘Деление на ноль.’ );
>
return 1 / $x ;
>
?php
try echo inverse ( 5 ) . «\n» ;
> catch ( Exception $e ) echo ‘Поймано исключение: ‘ , $e -> getMessage (), «\n» ;
> finally echo «Первый блок finally.\n» ;
>
try echo inverse ( 0 ) . «\n» ;
> catch ( Exception $e ) echo ‘Поймано исключение: ‘ , $e -> getMessage (), «\n» ;
> finally echo «Второй блок finally.\n» ;
>
// Продолжение нормального выполнения
echo «Привет, мир\n» ;
?>
Результат выполнения данного примера:
0.2 Первый блок finally. Поймано исключение: Деление на ноль. Второй блок finally. Привет, мир
Пример #4 Взаимодействие между блоками finally и return
function test () try throw new Exception ( ‘foo’ );
> catch ( Exception $e ) return ‘catch’ ;
> finally return ‘finally’ ;
>
>
Результат выполнения данного примера:
finally
Пример #5 Вложенные исключения
class MyException extends Exception
class Test public function testing () try try throw new MyException ( ‘foo!’ );
> catch ( MyException $e ) // повторный выброс исключения
throw $e ;
>
> catch ( Exception $e ) var_dump ( $e -> getMessage ());
>
>
>
$foo = new Test ;
$foo -> testing ();
Результат выполнения данного примера:
string(4) "foo!"
Пример #6 Обработка нескольких исключений в одном блоке catch
class MyException extends Exception
class MyOtherException extends Exception
class Test public function testing () try throw new MyException ();
> catch ( MyException | MyOtherException $e ) var_dump ( get_class ( $e ));
>
>
>
$foo = new Test ;
$foo -> testing ();
Результат выполнения данного примера:
string(11) "MyException"
Пример #7 Пример блока catch без указания переменной
Допустимо начиная с PHP 8.0.0
class SpecificException extends Exception <>
function test () throw new SpecificException ( ‘Ой!’ );
>
try test ();
> catch ( SpecificException ) print «Было поймано исключение SpecificException, но нам безразлично, что у него внутри.» ;
>
?>
Пример #8 Throw как выражение
Допустимо начиная с PHP 8.0.0
function test () do_something_risky () or throw new Exception ( ‘Всё сломалось’ );
>
try test ();
> catch ( Exception $e ) print $e -> getMessage ();
>
?>
User Contributed Notes 14 notes
14 years ago
If you intend on creating a lot of custom exceptions, you may find this code useful. I’ve created an interface and an abstract exception class that ensures that all parts of the built-in Exception class are preserved in child classes. It also properly pushes all information back to the parent constructor ensuring that nothing is lost. This allows you to quickly create new exceptions on the fly. It also overrides the default __toString method with a more thorough one.
interface IException
/* Protected methods inherited from Exception class */
public function getMessage (); // Exception message
public function getCode (); // User-defined Exception code
public function getFile (); // Source filename
public function getLine (); // Source line
public function getTrace (); // An array of the backtrace()
public function getTraceAsString (); // Formated string of trace
/* Overrideable methods inherited from Exception class */
public function __toString (); // formated string for display
public function __construct ( $message = null , $code = 0 );
>
abstract class CustomException extends Exception implements IException
protected $message = ‘Unknown exception’ ; // Exception message
private $string ; // Unknown
protected $code = 0 ; // User-defined exception code
protected $file ; // Source filename of exception
protected $line ; // Source line of exception
private $trace ; // Unknown
public function __construct ( $message = null , $code = 0 )
if (! $message ) throw new $this ( ‘Unknown ‘ . get_class ( $this ));
>
parent :: __construct ( $message , $code );
>
public function __toString ()
return get_class ( $this ) . » ‘ < $this ->message > ‘ in < $this ->file > ( < $this ->line > )\n»
. » < $this ->getTraceAsString ()> » ;
>
>
?>
Now you can create new exceptions in one line:
class TestException extends CustomException <>
?>
Here’s a test that shows that all information is properly preserved throughout the backtrace.
function exceptionTest ()
try throw new TestException ();
>
catch ( TestException $e ) echo «Caught TestException (‘ < $e ->getMessage ()> ‘)\n < $e >\n» ;
>
catch ( Exception $e ) echo «Caught Exception (‘ < $e ->getMessage ()> ‘)\n < $e >\n» ;
>
>
echo ‘
' . exceptionTest () . '
‘ ;
?>
Here’s a sample output:
Caught TestException (‘Unknown TestException’)
TestException ‘Unknown TestException’ in C:\xampp\htdocs\CustomException\CustomException.php(31)
#0 C:\xampp\htdocs\CustomException\ExceptionTest.php(19): CustomException->__construct()
#1 C:\xampp\htdocs\CustomException\ExceptionTest.php(43): exceptionTest()
#2
