calling exec on a php file and passing parameters?

前端 未结 5 1688
慢半拍i
慢半拍i 2021-02-19 00:53

I am wanting to call a php file using exec.

When I call it I want to be able to pass a variable through (an id).

I can call echo exec(\"php /var/www/unity/

5条回答
  •  庸人自扰
    2021-02-19 00:55

    I know this is an old thread but it helped me solve a problem so I want to offer an expanded solution. I have a php program that is normally called through the web interface and takes a long list of parameters. I wanted to run it in the background with a cron job using shell_exec() and pass a long list of parameters to it. The parameter values change on each run.

    Here is my solution: In the calling program I pass a string of parameters that look just like the string a web call would send after the ?. example: sky=blue&roses=red&sun=bright etc. In the called program I check for the existence of $argv[1] and if found I parse the string into the $_GET array. From that point forward the program reads in the parameters just as if they were passed from a web call.

    Calling program code:

    $pars = escapeshellarg($pars); // must use escapeshellarg()
    $output = shell_exec($php_path . ' path/called_program.php ' . $pars); // $pars is the parameter string
    

    Called program code inserted before the $_GET parameters are read:

    if(isset($argv[1])){ // if being called from the shell build a $_GET array from the string passed as $argv[1]
        $args = explode('&', $argv[1]); // explode the string into an array of Type=Value elements
        foreach($args as $arg){
            $TV = explode('=', $arg); // now explode each Type and Value into a 2 element array
            $_GET[$TV[0]] = $TV[1]; // set the indexes in the $_GET array
            }
        }
    //------------------------
    // from this point on the program processes the $_GET array normally just as if it were passed from a web call.
    

    Works great and requires minimal changes to the called program. Hope someone finds it of value.

提交回复
热议问题