PHP.mk документација

exit

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.exit.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.exit.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
exit

Референца за `function.exit.php` со подобрена типографија и навигација.

function.exit.php

exit

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

exitПрекинете ја тековната скрипта со код за статус или порака

= NULL

exit(string|int $status = 0): never

Го прекинува извршувањето на скриптата. Функции за исклучување and деструктори на објекти секогаш ќе бидат извршени дури и ако exit() се повика. Сепак, finally блоковите никогаш не се извршуваат.

Код за излез од 0 се користи за да се покаже дека програмата успешно ги завршила своите задачи. Секоја друга вредност укажува на некаква грешка што се случила за време на извршувањето.

exit() е специјална функција, бидејќи има посветен токен во парсерот, така што може да се користи како изјава (т.е. без загради) за да се прекине скриптата со стандарден код за статус.

Безбедност: стандардниот сет на знаци

Не е можно да се оневозможи, или да се создаде именски простор што го засенува глобалниот exit() function.

Параметри

status
Враќа status е стринг, оваа функција го печати status пред излезот. Кодот за излез вратен од PHP е 0.

Враќа status е int, кодот за излез вратен од PHP ќе биде status.

Забелешка: Кодовите за излез треба да бидат во опсег 0 to 254, кодот за излез 255 е резервиран од PHP и не треба да се користи.

Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

Пред PHP 8.4.0, exit() не следеше стандардното семантика на мешање типови на PHP, ниту почитувај ги strict_types declare.

Било која вредност што не е од типот int беше претворена во string including resource and array вредности. Од PHP 8.4.0, ги следи вообичаените семантики за префрлање типови и фрла TypeError на невалидни вредности.

Вратени вредности

Бидејќи ова го прекинува PHP скриптот, не се враќа вредност.

Дневник на промени

Верзија = NULL
8.4.0 exit() сега е правилна функција, затоа ги следи вообичаените семантика на мешање типови на PHP е под влијание на strict_types декларирај, може да се повика со именувани аргументи и да биде Бидејќи ова е конструкција на јазикот, а не функција, не може да се повика користејќи.

Примери

Пример #1 Основен exit() example

<?php

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

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

?>

Пример #2 exit() пример со string

<?php

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

?>

Пример #3 Функциите за исклучување и деструкторите се извршуваат без оглед

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

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

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

Пример #4 exit() како изјава

<?php

// exit program normally with exit code 0
exit;

?>

Белешки

Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

Пред PHP 8.4.0, exit() беше јазична конструкција и не функција, затоа не беше можно да се повика со користење Бидејќи ова е конструкција на јазикот, а не функција, не може да се повика користејќи, или именувани аргументи.

Види Исто така

Белешки од корисници — Интерпретира стринг од XML во објект

dexen dot devries на gmail точка ком
пред 15 години
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()

?>
алберт на removethis точка peschar точка net
пред 16 години
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;
}

?>
theonenk at gmail dot com
пред 10 години
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
винсент точка laag на gmail точка com
пред 15 години
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.
емилс на tvnet точка lv
пред 22 години
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.
tianyiw на vip dot qq dot com
3 години пред
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
devinemke at devinemke dot com
пред 17 години
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
chris на ocproducts dot com
пред 8 години
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.
void a t informance d o t info
figroc at gmail dot com
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');
жан точка клаво на gmail точка com
пред 6 години
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
freecorvette at gmail dot com
пред 13 години
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.";
?>
Бил Гејтс на hotmail точка com
пред 4 години
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
м точка libergolis на gmail точка com
пред 10 години
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.
sunfundev на gmail точка com
пред 8 години
>> 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
?>
григ-сирен на rambler точка ru
пред 5 месеци
NOTE!!!
If module UOPZ (User Operations for Zend) is installed and active - function exit() is disabled by this module by default. So call to exit() function will NOT terminate program. This can lead to unpredictable and unexpectable results. See description of function uopz_allow_exit() for details.
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.