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
| Parameter | Description |
|---|---|
| status | Optional. 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 |
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:
Line 1
Script stopped here.
Example #2: Exit without a message
<?php
echo "Before exit";
exit;
echo "After exit";
?>
Output:
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:
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:
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.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |