Open Laboratory for Technocrats

Grab the developer role, learn concepts & prepare with senior software engineers to get solutions for problems in a software job. Coding and Programming Solutions crafted for you.

PHP - Script is running from where ?

How to check if the code which is running is from a web-server or via command line[Terminal]  in PHP?

There are cases where we need to change the script as per the demand of web-server action or CLI action.

In PHP language lets have a look to the solution.

php_sapi_name, which gives us the information about the script from where it is running.

Example :

<?php
    echo php_sapi_name();
?>

We will see the result as cli if the terminal executes this script.
Similarly we can check the different types of sources from where the script is executed with the hello of the function.

Few more methods to check are as :
1. Via STDIN
if(defined('STDIN') )
     echo("Running from CLI");
else
     echo("Not Running from CLI");
2.Via SAPI Constant
if (PHP_SAPI === 'cli')
     echo("Running from CLI");
else
     echo("Not Running from CLI");
3.Via SAPI Function
if(php_sapi_name()==="cli")
     echo("Running from CLI");
else
     echo("Not Running from CLI");

Top #3 Articles

Most Read