What are the best practices for determining whether a PHP script is running locally or on a web server?

To determine whether a PHP script is running locally or on a web server, you can check the value of the $_SERVER['SERVER_NAME'] variable. If it is set to 'localhost' or an IP address, then the script is likely running locally. If it is set to a domain name, then the script is running on a web server.

if ($_SERVER['SERVER_NAME'] === 'localhost' || filter_var($_SERVER['SERVER_NAME'], FILTER_VALIDATE_IP)) {
    echo 'Running locally';
} else {
    echo 'Running on a web server';
}