exit() function in PHP

The exit() function in PHP prints a message and terminates the current script execution immediately. It can accept an optional message parameter to display before exiting.

Syntax

exit(msg)

Parameters

  • msg − Optional. The message to display before exiting the script. Can be a string or an integer exit status code.

Return Value

The exit() function does not return any value as it terminates script execution.

Example 1: Basic Usage

Here's a simple example showing how exit() works −

<?php
    echo "Before exit";
    exit("Script terminated!");
    echo "This line will never execute";
?>
Before exit
Script terminated!

Example 2: File Operation with Error Handling

The exit() function is commonly used for error handling when operations fail −

<?php
    $url = "https://www.example.com/";
    fopen($url, "r") 
    or exit("Can't connect!");
    echo "Connection successful!";
?>
Can't connect!

Example 3: Using Exit Status Code

You can also pass an integer exit status code instead of a message −

<?php
    $condition = false;
    if (!$condition) {
        exit(1); // Exit with error status code 1
    }
    echo "This won't be displayed";
?>

Conclusion

The exit() function is essential for controlling script flow and handling errors. Use it to terminate execution when critical errors occur or when certain conditions are not met.

Updated on: 2026-03-15T07:36:15+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements