exit

(PHP 4, PHP 5)

exitBir ileti çıktılayıp çalışmakta olan betiği sonlandırır

Açıklama

void exit ([ string $durum ] )
void exit ( int $durum )

Betiğin çalışmasını bitirir.

Değiştirgeler

durum

durum bir dizge ise işlev betiği sonlandırmadan önce bu dizgeyi basar.

status bir tamsayı ise bu değer çıkış durumu olarak kullanılır. Çıkış durumları 0..254 arasında olmalıdır. Çıkış durumu 255 PHP'nin kendi kullanımına ayrılmış olup kullanılmamalıdır. Durum 0, betiğin işini başarıyla yerine getirdiği anlamına gelir.

Bilginize: PHP >= 4.2.0 sürümlerinde durum tamsayı ise bu sayı basılmaz.

Dönen Değerler

Hiçbir değer dönmez.

Örnekler

Örnek 1 - exit() örneği

<?php

$filename 
'/dosya/yolu/veri/dosyası';
$file fopen($filename'r')
    or exit(
"($filename) dosyası açılamadı");

?>

Örnek 2 - Çıkış durumu örneği

<?php

// Betik normal olarak sonlansın
exit;
exit();
exit(
0);

// Bir hata koduyla sonlansın
exit(1);
exit(
0376); // sekizlik

?>

Notlar

Bilginize: Bu bir işlev değil, dil oluşumu olduğundan değişken işlevler kullanılarak çağrılamaz.

Bilginize:

Bu bir dil oluşumu olup die() ile eşdeğerdir.

Ayrıca Bakınız

add a note add a note

User Contributed Notes 13 notes

up
11
void a t informance d o t info
5 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:
<?php
define
('INDEX', true);
?>

in your included file:
<?php
if (!defined('INDEX')) {
   die(
'You cannot call this script directly !');
}
?>

BR.

Ninj
up
7
vincent dot laag at gmail dot com
3 years ago
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.
up
3
alexyam at live dot com
2 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:

<?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.";
?>
up
2
albert at removethis dot peschar dot net
5 years ago
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;
}

?>
up
2
nicoladinh at gmail dot com
3 years ago
Calling to exit() will flush all buffers started by ob_start() to default output.
up
1
dexen dot devries at gmail dot com
3 years ago
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()

?>
up
1
devinemke at devinemke dot com
12 years ago
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');
up
0
matt at serverboy dot net
4 years ago
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:

<?php

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:

index.php:
<?php

switch(true) {
    case
true:
        require(
'application.php');
}

?>

application.php:
<?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.
up
0
emils at tvnet dot lv
10 years ago
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.
up
0
mbostrom at paragee dot com
11 years ago
In PHP 4.3.1 (and possibly 4.3.0), running scripts from the command line works a lot better.  This is probably because 4.3.x has a whole new CLI mode.

Specifically, exit status is now returned (to the shell) as you would expect.  This is a godsend for writing embedded email processing scripts, as much email infrastructure (fetchmail, qmail, mutt, etc.) is dependant upon correctly returned status codes, and the inability to return a status code (as in PHP 4.2.x) is an insurmountable obstacle.

$_SERVER["argv"] is also always available in 4.3.x, I think, whereas in 4.2.x php.ini could prevent it from being available.

(On the downside, I had to ./configure --without-mysql in order to get 4.3.1 to compile on RedHat 8.0.  Otherwise there was what looked like a fatal compile warning (that I might also have been able to ignore somehow).

The "fatal warning" FYI:
ext/mysql/libmysql/my_tempnam.o: In function `my_tempnam':
ext/mysql/libmysql/my_tempnam.c:103: the use of `tempnam' is dangerous, better use `mkstemp'

Changing the code from tempnam to mkstemp would probably not be overly complicated, but it is non-trivial.)
up
0
shaun at NOshatSPAM dot net
11 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.
up
-2
jbezNULLorg at gmNULLail dot com
5 years ago
If you are retroactively going through included files to prevent them from being accessed, you can use the following.

<?php
if($_SERVER['SCRIPT_FILENAME'] == __FILE__ )
   
header('location: /'); // or exit();

// rest of code

?>
up
-11
Jorge Castro
1 year ago
Another way to avoid exit is to add a conditional branch (i.e. an if).

<?php
    $task
=someoperation();
    if (!
$task) {
       
// for example, the task failed so we exit asap.
       
exit();
    }
   
//... rest of the code...
?>

is analog to :

<?php
    $task
=someoperation();
    if (!
$task) {
       
// the task failed, so we do nothing and "jump" to the end of the code
        //... rest of the code...
   
}
?>

Most of the case, to use exit is cleaner than to add a big branch.
To Top