Как завершить php скрипт

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

function shutdown ()
echo ‘Завершить: ‘ . __FUNCTION__ . ‘()’ . PHP_EOL ;
>

$foo = new Foo ();
register_shutdown_function ( ‘shutdown’ );

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

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

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

Примечания

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

Замечание:

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

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

User Contributed Notes 21 notes

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()

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

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).

echo «testing finally wit exit\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

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.

Beware if you enabled uopz extension, it disables exit / die() by default. They are just «skipped».

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.

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.

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.

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.» ;
?>

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.

include (‘header.php’);
blah blah blah
if (!$mysql_connect) echo «unable to connect»;
include (‘footer.php’);
exit;
>
blah blah blah
include (‘footer.php’);

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

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.

>> 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» ;
>
>

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

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.

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.

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 — это конструкция языка, и она может быть вызвана без круглых скобок если не передается параметр status .

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

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

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

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

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

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

Примеры

Пример #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 ;
>
>

function shutdown ()
echo ‘Завершить: ‘ . __FUNCTION__ . ‘()’ . PHP_EOL ;
>

$foo = new Foo ();
register_shutdown_function ( ‘shutdown’ );

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

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

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

Примечания

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

Замечание:

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

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

Источник

PHP exit() Function

The exit() function prints a message and terminates the current script.

Syntax

Parameter Values

Parameter Description
message Required. A message or status number to print before terminating the script. A status number will not be written to the output, just used as the exit status.

Technical Details

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Читайте также:  Https oxc ecosafety ru ox6 ox html
Оцените статью