PHP exit() Function

PHP exit() stops the current script immediately. It can also print a message before stopping.

You can use exit() when something goes wrong and there is no point to run the remaining code. It is also used after redirecting the user to another page. The die() function is an alias of exit(), so both works exactly same.


Syntax

exit(string|int $status = ""): never

Parameters

ParameterDescription
statusOptional. If it is a string, PHP prints it and then stops the script. If it is an integer (0 to 254), it is used as the exit status, mainly for command line scripts. Status 0 means success and is not printed
Note: exit is a language construct, so brackets are optional. exit; and exit(); both are valid.

Examples

Example #1: Exit with a message

The line after exit() never runs.

<?php
echo "Line 1<br>";

exit("Script stopped here.");

echo "Line 2<br>"; // this line will not run
?>

Output:

Tutorials Class - Output Window

Line 1
Script stopped here.


Example #2: Exit without a message

<?php
echo "Before exit";

exit;

echo "After exit";
?>

Output:

Tutorials Class - Output Window

Before exit


Example #3: Using die() when a file is missing

This is a very common way to stop the script if a required file is not found.

<?php
$file = "data.txt";

if (!file_exists($file)) {
    die("File not found: " . $file);
}

echo "File found";
?>

Output:

Tutorials Class - Output Window

File not found: data.txt


Example #4: Stop page for guest user

If the user is not logged in, we show a message and stop. The dashboard code below it is not executed.

<?php
$loggedIn = false;

if (!$loggedIn) {
    echo "Please login first.";
    exit;
}

echo "Welcome to your dashboard.";
?>

Output:

Tutorials Class - Output Window

Please login first.


What happens after exit()?

PHP stops running your normal code, but shutdown functions (set by register_shutdown_function()) and object destructors still run.

Also remember to call exit() after a redirect. Read more in PHP header() function.


Summary

  • exit() stops the script immediately.
  • A string message is printed, an integer is used as exit status.
  • die() is an alias of exit().
  • Brackets are optional.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.