What is exit()
Function in PHP? | Complete Guide with Examples
The exit()
function in PHP is used to terminate the current script immediately. It is often used when you want to stop the execution of a program if certain conditions are met, or after an error occurs. You can also output a message before the script exits.
In this article, we’ll explain the exit()
function in PHP with simple examples to help you understand how and when to use it.
Syntax of exit()
in PHP
exit();
exit(string $message);
- If you pass a string, it will be printed before exiting.
- If you don't pass anything, PHP will simply terminate the script.
Key Points About exit()
Function
exit()
is language construct, not a function, so parentheses are optional.- It is equivalent to
die()
in PHP. - You can use it for error handling, user authentication checks, or stopping execution after critical failures.
PHP exit()
Function Examples
1. Basic Example Without a Message
<?php
echo "Hello World!";
exit();
echo "This will not be executed.";
?>
Output:
Hello World!
The second
echo
will not be executed because the script stops atexit()
.
2. exit()
With a Custom Message
<?php
$age = 15;
if ($age < 18) {
exit("You must be at least 18 years old to access this page.");
}
echo "Welcome to the site!";
?>
Output if $age
is 15:
You must be at least 18 years old to access this page.
The script stops after displaying the message.
3. Using exit
Inside a Conditional Statement
<?php
$is_logged_in = false;
if (!$is_logged_in) {
exit("Access Denied: Please login to continue.");
}
echo "Welcome back, User!";
?>
Output:
Access Denied: Please login to continue.
If a user is not logged in, the system immediately halts further processing.
Practical Use Cases for exit()
in PHP
- Error Handling: Exit if a database connection fails.
- Authentication: Stop script if the user is not authorized.
- Maintenance Mode: Show a maintenance message and exit.
- Form Validation: Exit if critical form fields are missing.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.