How can PHP scripts differentiate between running via Crontab or a web server?

PHP scripts can differentiate between running via Crontab or a web server by checking the presence of certain environment variables that are typically set by the web server. One common approach is to check for the $_SERVER['DOCUMENT_ROOT'] variable, which is set by the web server but not by Cron. Another way is to check for the $_SERVER['REMOTE_ADDR'] variable, which is set by the web server when running via HTTP request. By checking these variables, the PHP script can determine how it is being executed and adjust its behavior accordingly.

if(isset($_SERVER['DOCUMENT_ROOT']) && !isset($_SERVER['REMOTE_ADDR'])) {
    // Script is running via web server
    echo "Running via web server";
} else {
    // Script is running via Cron
    echo "Running via Cron";
}