In PHP how can I detect code is being run from command line?

Check php_sapi_name(). If it =='cli', then you are calling from the command line.

http://php.net/manual/en/function.php-sapi-name.php