Php прекратить выполнение скрипта. Фоновое выполнение скрипта на PHP без crontab

Останавливает выполнение PHP скрипта и выводит отформатированное HTML сообщение.

Аналог базовой PHP функции die(). Разница в том, что wp_die() выводит отформатированную HTML страницу ошибки. Рекомендуется использовать эту функцию, когда нужно полностью прекратить работу PHP. Не рекомендуется пользоваться этой функцией часто - старайтесь не показывать ошибки пользователям.

Возвращает

Ничего не возвращает, а обрывает работу PHP.

Использование wp_die($message, $title, $args); $message(смешанный) Сообщение об ошибке или полный объект класса WP_Error.
По умолчанию: "" $title(строка/массив/число/объект/логический) Заголовок ошибки. Если используете объект WP_Error, то заголовок будет взят из $data["title"], этот параметр можно заранее изменить под себя.
По умолчанию: "" $args(строка/массив)

Различные аргументы контролирующие поведение.
По умолчанию: нет

    response (число)
    Код состояния HTTP. 500 - внутренняя ошибка сервера. Весь список .
    По умолчанию: 500

    back_link (логический)
    Выводить или нет обратную ссылку на предыдущую страницу.
    По умолчанию: false

  • text_direction (строка)
    Направление текста: ltr (слева направо) или rtl (справа налево).
    По умолчанию: "ltr"
Примеры #1. Демонстрация использования

Используя функцию wp_die() , посмотрим что находиться в глобальной переменной $post в данный момент:

Add_filter("body_class", "add_body_class_cb"); function add_body_class_cb($classes) { global $post; wp_die("" . var_export($post, true) . ""); }

#2. Стилизация wp_die блока

Если на сайте нужно изменить дизайн этого блока, то можно воспользоваться хуком wp_die_handler :

html { background: #f1f1f1; } body { background: #fff; color: #444; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif; margin: 2em auto; padding: 1em 2em; max-width: 700px; -webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.13); box-shadow: 0 1px 3px rgba(0,0,0,0.13); } h1 { border-bottom: 1px solid #dadada; clear: both; color: #666; font-size: 24px; margin: 30px 0 0 0; padding: 0; padding-bottom: 7px; } #error-page { margin-top: 50px; } #error-page p { font-size: 14px; line-height: 1.5; margin: 25px 0 20px; } #error-page code { font-family: Consolas, Monaco, monospace; } ul li { margin-bottom: 10px; font-size: 14px ; } a { color: #0073aa; } a:hover, a:active { color: #00a0d2; } a:focus { color: #124964; -webkit-box-shadow: 0 0 0 1px #5b9dd9, 0 0 2px 1px rgba(30, 140, 190, .8); box-shadow: 0 0 0 1px #5b9dd9, 0 0 2px 1px rgba(30, 140, 190, .8); outline: none; } .button { background: #f7f7f7; border: 1px solid #ccc; color: #555; display: inline-block; text-decoration: none; font-size: 13px; line-height: 26px; height: 28px; margin: 0; padding: 0 10px 1px; cursor: pointer; -webkit-border-radius: 3px; -webkit-appearance: none; border-radius: 3px; white-space: nowrap; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; -webkit-box-shadow: 0 1px 0 #ccc; box-shadow: 0 1px 0 #ccc; vertical-align: top; } .button.button-large { height: 30px; line-height: 28px; padding: 0 12px 2px; } .button:hover, .button:focus { background: #fafafa; border-color: #999; color: #23282d; } .button:focus { border-color: #5b9dd9; -webkit-box-shadow: 0 0 3px rgba(0, 115, 170, .8); box-shadow: 0 0 3px rgba(0, 115, 170, .8); outline: none; } .button:active { background: #eee; border-color: #999; -webkit-box-shadow: inset 0 2px 5px -3px rgba(0, 0, 0, 0.5); box-shadow: inset 0 2px 5px -3px rgba(0, 0, 0, 0.5); -webkit-transform: translateY(1px); -ms-transform: translateY(1px); transform: translateY(1px); }

10 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:


in your included file:


BR.

4 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:



This will print:

testing finally wit exit
In try, exiting

1 year 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:


// Exit into desctructor:

17 years ago

If you are using templates with numerous includes then exit() will end you script and your template will not complete (no , , 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().

include ("header.php");
blah blah blah
if (!$mysql_connect) {
echo "unable to connect";
include ("footer.php");
exit;
}
blah blah blah
include ("footer.php");

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

3 years ago

In addition to "void a t informance d o t info", here"s a one-liner that requires no constant:



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

To redirect to / instead of dying:



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.

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