php завершить выполнение скрипта
Php завершить выполнение скрипта
(PHP 4, PHP 5, PHP 7, PHP 8)
exit — Вывести сообщение и прекратить выполнение текущего скрипта
Описание
Список параметров
Если status задан в виде строки, то эта функция выведет содержимое status перед выходом.
Если status задан в виде целого числа ( int ), то это значение будет использовано как статус выхода и не будет выведено. Статусы выхода должны быть в диапазоне от 0 до 254, статус выхода 255 зарезервирован PHP и не должен использоваться. Статус выхода 0 используется для успешного завершения программы.
Возвращаемые значения
Функция не возвращает значения после выполнения.
Примеры
Пример #1 Пример использования exit
Пример #2 Пример использования exit со статусом выхода
//обычный выход из программы
exit;
exit();
exit( 0 );
//выход с кодом ошибки
exit( 1 );
exit( 0376 ); //восьмеричный
Пример #3 Функции выключения и деструкторы выполняются независимо
$foo = new Foo ();
register_shutdown_function ( ‘shutdown’ );
exit();
echo ‘Эта строка не будет выведена.’ ;
?>
Результат выполнения данного примера:
Примечания
Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.
Смотрите также
User Contributed Notes 20 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.
if ( SOME_EXIT_CONDITION )
throw new SystemExit (); // instead of exit()
jbezorg at gmail proposed the following:
?>
After sending the `Location:’ header PHP _will_ continue parsing, and all code below the header() call will still be executed. So instead use:
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» ;
echo «In the end\n» ;
?>
This will print:
testing finally wit exit
In try, exiting
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:
Beware if you enabled uopz extension, it disables exit / die() by default. They are just «skipped».
>> 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 ;
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:
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.» ;
?>
exit — Выводит сообщение и прекращает выполнение текущего скрипта
Описание
Прекращает выполнение скрипта. Функции отключения и деструкторы объекта будут запущены даже если была вызвана конструкция exit.
Список параметров
Если параметр status задан в виде строки, то эта функция выведет содержимое status перед выходом.
Если параметр status задан в виде целого числа ( integer ), то это значение будет использовано как статус выхода и не будет выведено. Статусы выхода должны быть в диапазоне от 0 до 254, статус выхода 255 зарезервирован PHP и не должен использоваться. Статус выхода 0 используется для успешного завершения программы.
Замечание: PHP >= 4.2.0 НЕ выведет параметр status если он задан как целое число ( integer ).
Возвращаемые значения
Эта функция не возвращает значения после выполнения.
Примеры
Пример #1 Пример использования exit
Пример #2 Пример использования exit со статусом выхода
//нормальный выход из программы
exit;
exit();
exit( 0 );
//выход с кодом ошибки
exit( 1 );
exit( 0376 ); //восьмеричный
Пример #3 Функции выключения и деструкторы выполняются независимо
$foo = new Foo ();
register_shutdown_function ( ‘shutdown’ );
exit();
echo ‘Эта строка не будет выведена.’ ;
?>
Результат выполнения данного примера:
Примечания
Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.
Смотрите также
Проблемы «долгих» скриптов PHP
Внешний таймаут
В первую очередь нужно установить подходящее значение параметра max_execution_time в конфиге PHP.
Веб-сервер может также проксировать запросы на другой веб-сервер, который и запустит PHP скрипт (не редкий пример, nginx — фронтенд, apache — бэкэнд). В этом случае на проксирующем веб-сервере необходимо также настраивать таймаут проксирования. Для apache ProxyTimeout, для nginx proxy_read_timeout.
Прерывание пользователем
Если скрипт запускается в ответ на HTTP-запрос, то пользователь может остановить выполнение запроса в своем браузере, в этом случае прекратит свою работу и PHP скрипт. Если же требуется, чтобы скрипт продолжил свою работу даже после остановки запроса, установите в TRUE параметр ignore_user_abort в конфиге PHP.
Потеря открытых соединений
В таких случаях следует в первую очередь попробовать увеличить таймаут соединения. Например, для MySQL можно выполнить запрос (спасибо Snowly)
Параллельный запуск
В таких случаях можно использовать блокировку используемых ресурсов, но эта задача всегда решается индивидуально. Либо можно просто проверять, не запущена ли другая копия этого скрипта, и либо подождать завершения его работы, либо завершить текущий запуск. Для этого можно просматривать список запущенных процессов, либо использовать блокировку запуска самого скрипта, что то вроде:
Нагрузка на веб-сервер
В случаях, когда долгие скрипты запускаются через веб-сервер, соединение клиента с этим самым веб-сервером остается открытым до тех пор, пока не отработает скрипт. Это не есть хорошо, т.к. задача веб-сервера как можно быстрее обработать запрос и отдать результат. Если же соединение остается висеть, то один из воркеров (процессов) веб-сервера на долгое время будет занят. А если одновременно будет запущено достаточно много таких скриптов, то они могут занять все (ну или почти все) свободные воркеры (для apache см. MaxClients), и веб-сервер просто не сможет обрабатывать другие запросы.
Поэтому следует при обработке запроса пользователя, запускать скрипт в фоновом режиме через php-cli, чтобы не нагружать веб-сервер, а пользователю отвечать что его запрос обрабатывается. При необходимости можно периодически проверять состояние обработки при помощи AJAX запросов.
Вот, пожалуй, и все что я могу рассказать по этой теме. Надеюсь, для кого-то будет полезным.
Php завершить выполнение скрипта
Музыка ВКонтакте запустила рекламную кампанию в формате 360°
State of SEO 2021: факторы ранжирования, тренды и планы на ближайший год
Например есть у меня script.php там 200 строк и в 55 строке условие, если например переменная равно 0 то все, прекратить выполнение всего скрипита.
либо весь скрипт обернуть в условие.
Rock’n’rolla:
Например есть у меня script.php там 200 строк и в 55 строке условие, если например переменная равно 0 то все, прекратить выполнение всего скрипита.
У вас присваивание, а не сравнение в операторе условия.
Учите матчасть. Вопросы детские до невозможности.
Rock’n’rolla, есть такая рекомендация, чтобы избегать ошибок связанных с путанием = и ==.
Рекомендуют вначале константы писать, а потом переменные:
Когда я был пионером в РНР, мне эта рекомендация очень помогла.
и верно подмечено, надо == писать, иначе if ($count = 0) всегда будет true возвращать
Если скрипт инклюжен откуда-то, то он остановит работу на этой строке, но родительский скрипт продолжит работу.
Работа с соединениями
Во время штатного выполнения PHP-скрипта установлен статус NORMAL. В случае, если удалённый клиент разорвал соединение, статус изменяется на ABORTED. Чаще всего отсоединение удалённого клиента происходит при нажатии кнопки «Stop» в браузере. В случае, если достигается установленный временной лимит (ознакомьтесь с функцией set_time_limit() ), будет установлен статус TIMEOUT.
User Contributed Notes 12 notes
hey, thanks to arr1, and it is very useful for me, when I need to return to the user fast and then do something else.
When using the codes, it nearly drive me mad and I found another thing that may affect the codes:
This is because the zlib is on and the content will be compressed. But this will not output the buffer until all output is over.
So, it may need to send the header to prevent this problem.
now, the code becomes:
//do processing here
sleep ( 5 );
echo( ‘Text user will never see’ );
//do some processing
?>
Closing the users browser connection whilst keeping your php script running has been an issue since 4.1, when the behaviour of register_shutdown_function() was modified so that it would not automatically close the users connection.
sts at mail dot xubion dot hu
Posted the original solution:
The solution is to explicitly turn off output buffering and clear the buffer prior to sending your header information.
Tested in:
IE 7.5730.11
Mozilla Firefox 1.81
I had a lot of problems getting a redirect to work, after which my script was intended to keep working in the background. The redirect to another page of my site simply would only work once the original page had finished processing.
I finally found out what was wrong:
The session only gets closed by PHP at the very end of the script, and since access to the session data is locked to prevent more than one page writing to it simultaneously, the new page cannot load until the original processing has finished.
Solution:
Close the session manually when redirecting using session_write_close():
( true );
set_time_limit ( 0 );
sleep ( 100 );
exit;
?>
But careful:
Make sure that your script doesn’t write to the session after session_write_close(), i.e. in your background processing code. That won’t work. Also avoid reading, remember, the next script may already have modified the data.
So try to read out the data you need prior to redirecting.
PHP changes directory on connection abort so code like this will not do what you want:
The point mentioned in the last comment isn’t always the case.
I have an order script that adds data to a InnoDB database (through MySQL) and only commits the transactions upon successful completion. Without ignore_user_abort(), I have had times when a user’s connection dropped during the processing phase. and their card was charged, but they weren’t added to my local DB.
So, it’s always safe to ignore any aborts if you are processing sensitive transactions that should go ahead, whether your user is «watching» on the other end or not.
in regards of posting from:
arr1 at hotmail dot co dot uk
if you use/write sessions you need to do this before:
(otherwise it does not work)
ignore_user_abort(TRUE);
instead of ignore_user_abort();
I was quite stuck when trying to make my script redirect the client to another URL and then continue processing. The reason was php-fpm. All possible buffer flushes did not work, unless I called fastcgi_finish_request();
sleep ( 5 ); // User won’t feel this sleep because he’ll already be away
// do some work after user has been redirected
?>
This simple function outputs a string and closes the connection. It considers compression using «ob_gzhandler»
It took me a little while to put this all together, mostly because setting the encoding to none, as some people noted here, didn’t work.
The CONNECTION_XXX constants that are not listed here for some reason are:
0 = CONNECTION_NORMAL
1 = CONNECTION_ABORTED
2 = CONNECTION_TIMEOUT
3 = CONNECTION_ABORTED & CONNECTION_TIMEOUT
connection_status() return ABORTED state ONLY if the client disconnects gracefully (with STOP button). In this case the browser send the RST TCP packet that notify PHP the connection is closed.
But. If the connection is stopped by networs troubles (wifi link down by exemple) the script doesn’t know that the client is disconnected 🙁
I’ve tried to use fopen(«php://output») with stream_select() on writting to detect write locks (due to full buffer) but php give me this error : «cannot represent a stream of type Output as a select()able descriptor»
So I don’t know how to detect correctly network trouble connection.
# Choose a database
mysql_select_db(‘someDatabase’) or die(‘Could not select database’);