What is the best practice to run a php script from a php script?

I would use the following code:

$SERVER_PATH = dirname(__FILE__);
shell_exec($PHP_LOCATION.' '.$SERVER_PATH."/script.php?k1=v1&k2=v2 > /dev/null 2>/dev/null &");

Where:

  • $PHP_LOCATION must contain the path to PHP,

  • $SERVER_PATH - current working directory (fortunately, the script to run is in the same directory),

  • > /dev/null 2>/dev/null &added to make this call asynchronous (taken from a question with asynchronous shell in PHP )

This code has two problems:

  • As far as I remember, it ?k1=v1&k2=v2will work only for a web call, so in this particular case the parameters will not be passed to the script.

  • I really don't know how to initialize a variable $PHP_LOCATIONin order to be flexible and work on most hosts.

I did some research on both issues:

1 -- 'parameters_string', script , . ?

2, PHP_BINARY, PHP 5.4+ ( 5.3). , PHP , script. , ( PHP 5.3) ?

EDIT 0

, ( PHP) :

PHP- :

  • PNG .

, , , , , ( script). script () ().

1

, forking. 1 2, . , , , . , - .

!

+4
1

, Linux, :

function getBinaryRunner($binary)
{
    return trim(shell_exec('which '.$binary));
}

, :

function checkIfCommandExists($command)
{
    $result = shell_exec('which '.$command);
    return !empty($result);
}

:

shell_exec() , , , , "GET" , "URI", - . , :

  • -. :

    //Yes, you will use wget or, better, curl to make web-request from CLI
    shell_exec('wget http://your.web-server.domain/script.php?foo=bar');
    

    : - DNS, . - , - script CLI -CLI-

  • $_SERVER script , CLI:

    shell_exec('/usr/bin/php /path/to/script.php foo bar');
    
    //inside your script.php you will see:
    //$_SERVER['argv'][0] is "script.php"
    //$_SERVER['argv'][1] is "foo"
    //$_SERVER['argv'][2] is "bar"
    

    , script , , , "" - CLI. , CLI , .

" "

PHP .php &, . , - . , , . , SIGHUP , , nohup. "" , , , .

+2

Source: https://habr.com/ru/post/1599046/


All Articles