PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 30, 2022

[FIXED] Detect if running from the command line in Laravel 5

 January 30, 2022     laravel-5, php     No comments   

Issue

I have a use case where we need to modify application flow if the application is being run from the command line via Artisan (migrations, seeds, route:list).

In Laravel 4 this could be done like this:

App::runningInConsole()

Is there an equivalent in Laravel 5?

Using the Environment (.env) variables isn't preferred in this case as these commands occasionally need to be run on production (pointing to production resources) and I'd prefer to avoid resorting to duplicate (.env.commandline) files.


Solution

You can use the PHP function php_sapi_name (http://php.net/manual/en/function.php-sapi-name.php), to found out if the script was launched from a command or not.

In your case, you should check something like

if (strpos(php_sapi_name(), 'cli') !== false) {
    // Run from command
}

You may have to check the doc to find the proper value to check in each case though. (It may differ sometimes, but basically there should always be a different output from a script launched through a command)



Answered By - Clément Malet
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing