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 :
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
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') )2.Via SAPI Constant
echo("Running from CLI");
else
echo("Not Running from CLI");
if (PHP_SAPI === 'cli')3.Via SAPI Function
echo("Running from CLI");
else
echo("Not Running from CLI");
if(php_sapi_name()==="cli")
echo("Running from CLI");
else
echo("Not Running from CLI");