Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP, how to detect the execution is from CLI mode or through browser ? [duplicate]

Tags:

php

I have a common script which Im including in my PHPcron files and the files which are accessing through the browser. Some part of the code, I need only for non cron files. How can I detect whether the execution is from CLI or through browser (I know it can be done by passing some arguments with the cron files but I dont have access to crontab). Is there any other way ?

like image 726
binoy Avatar asked Jan 02 '10 11:01

binoy


People also ask

What is PHP CLI mode?

PHP CLI is a short for PHP Command Line Interface. As the name implies, this is a way of using PHP in the system command line. Or by other words it is a way of running PHP Scripts that aren't on a web server (such as Apache web server or Microsoft IIS). People usually treat PHP as web development, server side tool.

How to GET command line arguments in php?

There are two predefined variables in PHP, called $argc and $argv , that you can use to work with command-line arguments. The variable $argc simply tells you the number of arguments that were passed to the script. Remember that the name of the script you are running is always counted as an argument.


1 Answers

Use the php_sapi_name() function.

if (php_sapi_name() == "cli") {     // In cli-mode } else {     // Not in cli-mode } 

Here are some relevant notes from the docs:

php_sapi_name — Returns the type of interface between web server and PHP

Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, cli-server, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.

like image 146
Alexander V. Ilyin Avatar answered Oct 21 '22 02:10

Alexander V. Ilyin