zeratool
zeratool

Reputation: 1281

How to check if a YII app is running from a console or from browser?

I'm new to YII framework and i'd like to know if there's way to know/check if you are running from console or in a browser?

Thanks!

Upvotes: 14

Views: 12309

Answers (7)

Sahith Vibudhi
Sahith Vibudhi

Reputation: 5205

I am using Yii 1 and I use this function to check

public static function isWebRequest()
{
    return Yii::app() instanceof CWebApplication;
}

public static function isConsoleRequest()
{
    return Yii::app() instanceof CConsoleApplication; //!self::isWebRequest();
}

I put these functions in a helper(Componenet) Class and I use it as:

if(MyRandomHelper::isConsoleRequest())
{
    Email::shoot();
}

Upvotes: 1

Petr Pánek
Petr Pánek

Reputation: 389

check Yii::$app->id

  • when running from console Yii::$app->id = 'app-console'
  • when running from frontend (browser) Yii::$app->id = 'app-frontend'

Upvotes: 2

BlueZed
BlueZed

Reputation: 859

This reply is a bit late but there is a Yii-specific way to do this:

In Yii1 you can do:

if (Yii::app() instanceof CConsoleApplication)

In Yii2 that would be:

 if (Yii::$app instanceof Yii\console\Application)

Hope that's useful to someone...

Upvotes: 16

Yasar Arafath
Yasar Arafath

Reputation: 625

You can use

if(is_a(Yii::$app,'yii\console\Application'))

for console, and

if(is_a(Yii::$app,'yii\web\Application'))

for web.

https://stackoverflow.com/a/30635800/4916039

Upvotes: 1

Tebe
Tebe

Reputation: 3214

The most efficient way seems to define in the root file index.php this line :

define ('WEBAPP', true)

Later you can check in any point the application

if (defined('WEBAPP')) {
 echo "This is webapp";
} else {
  echo "app was launched via console";
}

Checked in Yii 1.7

Upvotes: 1

acorncom
acorncom

Reputation: 5955

You should also be able to do:

echo get_class(Yii::app());

which will tell you what type of app you're in ...

Upvotes: 8

ethan
ethan

Reputation: 975

Same way you would determine if a PHP application is being run in the console or not.

What is the canonical way to determine commandline vs. http execution of a PHP script?

Upvotes: 5

Related Questions