- PHP exit() Function
- PHP exit() Function
- Definition and Usage
- Syntax
- Parameter Values
- Technical Details
- How to exit from a specific function in PHP?
- How do I close a connection early?
- fastcgi_finish_request()
- PHP — exit from IF block
- exit
- Список параметров
- Возвращаемые значения
- Примеры
- Примечания
- Смотрите также
- PHP exit() Function
- Syntax
- Parameter Values
- Technical Details
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
PHP exit() Function
Web server immediately starts to transfer response «slowly and sadly» to the client, and php at the same time can do a lot of useful things in the context of a query, such as saving the session, converting the downloaded video, handling all kinds of statistics, etc. can invoke executing shutdown function. Acceleration is possible when there are actions in the process of script execution that do not affect server response.
PHP exit() Function
Example
Print a message and exit the current script:
Definition and Usage
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
Working of exit Function in PHP with Examples, Introduction to PHP exit. Whenever there is a need to terminate the current script along with a message in PHP, we make use of an inbuilt function called exit function in PHP, though exit function is used to terminate the current script, it does not interrupt the object destructors and shut down functions from being …
How to exit from a specific function in PHP?
I have multiple nested methods inside a PHP class. What I want to do is, based on certain circumstances, I want to exit from NOT JUST the current method, but 2 above it, then the leftover code should continue running. Now the issue with die(), exit() is that they end the full script and I don’t want that. I simply want to go a few methods up and continue the script.
Of course, there’s the old school method of returning a value in each method and check if it’s false for example. But that way I’ll have to write tons of additional code if I have like 50 nested methods. Here’s what I have right now — it’s a very basic usage here, I’m using it in a lot more complicated scenarios (using PHP 7.2.4):
class Sites < public function __construct() < $this->fn1(); > public function fn1() < $fn2 = $this->fn2(); echo 'I want this to be displayed no matter what!'; > public function fn2() < $fn3 = $this->fn3(); if ($fn3) < return true; >> public function fn3() < $fn4 = $this->fn4(); if ($fn4) < return true; >> public function fn4() < $random = rand(1, 100); if ($random >50) < return true; >else < // I want to exit/break the scirpt to continue running after // the $fn2 = $this->fn2() call in the $this->fn1() function. exit(); echo "This shouldn't be displayed."; > > >
Just as mentioned in the code comments, I want to break the script — if the random number is below 50 and go back to fn1() but continue executing the echo function there.
Is this possible somehow? Please let me know if you need more information and I’ll provide.
You can use Exceptions to do this, not particularly elegant, but this should do what your after, replace these methods.
public function fn1() < try < $fn2 = $this->fn2(); > catch ( Exception $e ) < >echo 'I want this to be displayed no matter what!'; > public function fn4() < $random = rand(1, 100); if ($random >50) < return true; >else < // I want to exit/break the scirpt to continue running after // the $fn2 = $this->fn2() call in the $this->fn1() function. //exit(); throw new Exception(); echo "This shouldn't be displayed."; > >
How about regular function call with a flag ?
class Sites < protected $flag = false; public function __construct() < $this->fn1(); > public function fn1() < if ($this->flag) < $this->flag = true; > else < echo 'I want this to be displayed no matter what!'; $fn2 = $this->fn2(); > > public function fn2() < $fn3 = $this->fn3(); if ($fn3) < return true; >> public function fn3() < $fn4 = $this->fn4(); if ($fn4) < return true; >> public function fn4() < $random = rand(1, 100); if ($random >50) < return true; >else < // I want to exit/break the scirpt to continue running after // the $fn2 = $this->fn2() call in the $this->fn1() function. //exit(); $this->flag = true; $this->fn1(); exit(); echo "This shouldn't be displayed."; > > > $sites = new Sites;
How can I exit from a php script and continue right, You can’t exit out of a script and continue running the same script. But some advice about your return statements: 1) If your function doesn’t return anything, then don’t put a return statement in there. 2) Use only one return statement per function, it will make your code more clear. Share.
How do I close a connection early?
I’m attempting to do an AJAX call (via JQuery) that will initiate a fairly long process. I’d like the script to simply send a response indicating that the process has started, but JQuery won’t return the response until the PHP script is done running.
I’ve tried this with a «close» header (below), and also with output buffering; neither seems to work. Any guesses? or is this something I need to do in JQuery?
The following PHP manual page (incl. user-notes) suggests multiple instructions on how to close the TCP connection to the browser without ending the PHP script:
Supposedly it requires a bit more than sending a close header.
OP then confirms: yup, this did the trick: pointing to user-note #71172 (Nov 2006) copied here:
Closing the users browser connection whilst keeping your php script running has been an issue since [PHP] 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:
Which works fine until you substitute phpinfo() for echo(‘text I want user to see’); in which case the headers are never sent!
The solution is to explicitly turn off output buffering and clear the buffer prior to sending your header information. Example:
Later on in July 2010 in a related answer Arctic Fire then linked two further user-notes that were-follow-ups to the one above:
- Connection Handling user-note #89177 (Feb 2009)
- Connection Handling user-note #93441 (Sep 2009)
It’s necessary to send these 2 headers:
Connection: close Content-Length: n (n = size of output in bytes )
Since you need know the size of your output, you’ll need to buffer your output, then flush it to the browser:
// buffer all upcoming output ob_start(); echo 'We\'ll email you as soon as this is done.'; // get the size of the output $size = ob_get_length(); // send headers to tell the browser to close the connection header('Content-Length: '.$size); header('Connection: close'); // flush all output ob_end_flush(); ob_flush(); flush(); // if you're using sessions, this prevents subsequent requests // from hanging while the background process executes if (session_id()) /******** background process starts here ********/
Also, if your web server is using automatic gzip compression on the output (ie. Apache with mod_deflate), this won’t work because actual Size of the output is changed, and the Content-Length is no longer accurate. Disable gzip compression the particular script.
For more details, visit http://www.zulius.com/how-to/close-browser-connection-continue-execution
You can use Fast-CGI with PHP-FPM to use the fastcgi_end_request() function. In this way, you can continue to do some processing while the response has already been sent to the client.
You find this in the PHP manual here: FastCGI Process Manager (FPM); But that function specifically is not further documented in the manual. Here the excerpt from the PHP-FPM: PHP FastCGI Process Manager Wiki:
fastcgi_finish_request()
This feature allows you to speed up implementation of some php queries. Acceleration is possible when there are actions in the process of script execution that do not affect server response. For example, saving the session in memcached can occur after the page has been formed and passed to a web server. fastcgi_finish_request() is a php feature, that stops the response output. Web server immediately starts to transfer response «slowly and sadly» to the client, and php at the same time can do a lot of useful things in the context of a query, such as saving the session, converting the downloaded video, handling all kinds of statistics, etc.
fastcgi_finish_request() can invoke executing shutdown function.
Note: fastcgi_finish_request() has a quirk where calls to flush , print , or echo will terminate the script early.
To avoid that issue, you can call ignore_user_abort(true) right before or after the fastcgi_finish_request call:
ignore_user_abort(true); fastcgi_finish_request();
ignore_user_abort(true);//avoid apache to kill the php running ob_start();//start buffer output echo "show something to user"; session_write_close();//close session file on server side to avoid blocking other requests header("Content-Encoding: none");//send header to avoid the browser side to take content as gzip format header("Content-Length: ".ob_get_length());//send length header header("Connection: close");//or redirect to some url: header('Location: http://www.google.com'); ob_end_flush();flush();//really send content, can't change the order:1.ob buffer to normal buffer, 2.normal buffer to output //continue do something on server side ob_start(); sleep(5);//the user won't wait for the 5 seconds echo 'for diyism';//user can't see this file_put_contents('/tmp/process.log', ob_get_contents()); ob_end_clean();
PHP | exit( ) Function, The exit () function in PHP is an inbuilt function which is used to output a message and terminate the current script. The exit () function only terminates the execution of the script. The shutdown functions and object destructors will always be executed even if exit () function is called. The …
PHP — exit from IF block
How can I exit a if block if a certain condition is met?
I tried using break but it doesn’t work:
if($bla): $bla = get_bla(); if(empty($bla)) break; do($bla); endif;
it says: Fatal error: Cannot break/continue 1 level in.
In PHP 5.3 you can use goto
if($bla): $bla = get_bla(); if(empty($bla)) goto end; do($bla); endif; end:
But personally I think that’s an ugly solution.
You can’t break if statements, only loops like for or while.
If this if is in a function, use ‘return’.
Why not just turn it around.
if($bla): $bla = get_bla(); if(!empty($bla)) < do($bla); >endif;
That way it will only run your code if $bla isn’t empty.. That’s kinda the point with if-statements
I cant believe no one have post this solution yet (writing it in my PHP style):
Php — How do I close a connection early?, fastcgi_finish_request () can invoke executing shutdown function. Note: fastcgi_finish_request () has a quirk where calls to flush, print, or echo will terminate the script early. To avoid that issue, you can call ignore_user_abort (true) right before or after the fastcgi_finish_request call: ignore_user_abort (true); …
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 ;
>
>
?php
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
COLOR PICKER
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.