PHP exit() | Stop Execution of Current File

The PHP exit() function is used, when we need to terminate the execution of current PHP script/file. For example:

<?php
   if(isset($_SESSION['user']))
   {
      // block of code to process user
   }
   else
   {
      header('Location: login.htm');
      exit();
      // some block of code
   }
   // other block of code
?>

Since the session variable user is not set, therefore the program flow goes to else block and the following two statements gets executed:

header('Location: login.htm');
exit();

The header() redirect the page to the login.htm page, whereas the exit() function skips the execution of remaining PHP script. That is, the execution of current PHP scripts stops, when an exit() function encounters.

The output of above PHP example, is shown in the snapshot given below:

php exit function

Since the header() function redirects to other page, that is login.htm page. Therefore, I think, I have to create another example of exit() function, that shows, how it terminates the execution of current PHP script:

<?php
   $x = 10;
   for($i=1; $i<$x; $i++)
   {
      if($i==4)
         exit();
      echo "The value of \$i is $i";
      echo "<BR>";
   }
   echo "The value of \$i is $i";
   echo "<BR>";
   echo "Some other text...";
   // some other block of code...
?>

The output of above PHP example, is shown in the snapshot given below:

php exit function

That is, when the value of $i becomes equal to 4, then the exit() function encounters, that terminates the execution of the current PHP scripts. Therefore, in above example, including remaining values of $i, the statements available right after the loop, also has not been executed.

PHP exit() Syntax

The syntax of exit() function in PHP, is:

exit(message|status);

That is, either we can display some message, before stopping the executing of current PHP script, or can provide some status code. The status code/number will not displayed on the output, rather it is used for exit status.

But let me tell you one thing that, when an exit(); statement encounters, then the execution of current PHP scripts halts/stops, but shutdown functions and object destructors will complete its execution.

Note - If you are not passing any status code or message to the exit() function, then you can write simply exit; to exit the program normally. That is:

all three statements does the same job, of exiting the program normally.

To print some message before exiting the program, follow the example given below:

<?php
   $x = 10;
   for($i=1; $i<$x; $i++)
   {
      if($i==4)
         exit("Exiting...");
      echo "The value of \$i is $i";
      echo "<BR>";
   }
   echo "The value of \$i is $i";
   echo "<BR>";
?>

The output should be:

The value of $i is 1
The value of $i is 2
The value of $i is 3
Exiting...

PHP Online Test


« Previous Tutorial Next Tutorial »