从CLI运行脚本,但阻止运行时,包括

问题描述:

我有一个PHP脚本,我经常使用CLI(普通SSH终端)运行。从CLI运行脚本,但阻止运行时,包括

<?php 

    class foo { 
     public function __construct() { 
      echo("Hello world"); 
     } 
    } 

    // script starts here... 
    $bar = new foo(); 

?> 

当我运行使用php filename.php代码中,我得到了停滞的预期Hello world。问题是,当我从其他PHP文件中包含文件时,我得到了同样的东西(我不想要)。

如何防止代码在文件包含时运行,但仍将其用作CLI脚本?

您可以测试$argv[0] == __FILE__以查看从命令行调用的文件是否与包含的文件相同。

class foo { 
    public function __construct() { 

     // Output Hello World if this file was called directly from the command line 
     // Edit: Probably need to use realpath() here as well.. 
     if (isset($argv) && realpath($argv[0]) == __FILE__) { 
     echo("Hello world"); 
     } 
    } 
} 

您可以使用PHP函数get_included_files和检查,如果你的文件是在阵列(使用in_array)

http://php.net/manual/en/function.get-included-files.php

我希望这可以帮助你。

你应该检查你是否都在CLI环境中运行,而不是“包含”。看到我的重写你的样品如下:

<?php 

    class foo { 
     public function __construct() { 
      echo("Hello world"); 
     } 
    } 

    // script starts here... 
    if (substr(php_sapi_name(), 0, 3) == 'cli' 
     && basename($argv[0]) == basename(__FILE__)) { 

     // this code will execute ONLY if the run from the CLI 
     // AND this file was not "included" 
     $bar = new foo(); 

    } 

?>