ThomasLC ThomasLC - 1 year ago 78
PHP Question

PHP passing parameters to a backgound script

i've been looking for quite a while on internet, but i cannot find a solution to my problem. I am pretty new to PHP, and I am having issues to run a php script in background.

Basically, I am getting POST data from JQuery ajax, I put it in a long string using escapeshellarg() on each variable and separated by spaces, and I call the script I want to process in background with exec() or shell_exec() functions (I tried both without any success...).

$arg_list = escapeshellarg($str_solution)." ";
$arg_list .= escapeshellarg($str_rubriques)." ";
$arg_list .= escapeshellarg($intervalle)." ";
$arg_list .= escapeshellarg($date_start)." ";
$arg_list .= escapeshellarg($date_end)." ";
$arg_list .= escapeshellarg($_SESSION['user_id'])." ";
$arg_list .= escapeshellarg($_SESSION['user_name']);

$output = shell_exec("/opt/plesk/php/5.6/bin/php-cgi -q script_rapports_intervalle.php ".$arg_list." &");

On the script_rapports_intervalle.php file, I just do :

print_r("here i am");


I do got a response from this script, as it displays only the "here i am" string. When I use a var_dump() on $argv, it says it is NULL. I have also tried to pass simple arguments like "foo" and "bar", but it seems that $argv is always equal to NULL.

Moreover, I saw many usages for processing a background script: putting "&" at the end of the command, or putting "| at now" instead. Wich one should I use ?

I guess I am surely doing things the wrong way, but I still cannot see where to fix the issues.

Thanks a lot for you help !

Answer Source

For me this simple code works

  $params = array("function_name" => 'image_detect',"image_guid" => $image_guid);

  $query_string = http_build_query($params, "", " ");
 if (PHP_OS === "WINNT") {
    pclose(popen("start /B php " . $script_location . " " . $query_string, "r"));
 } else {
    exec("/opt/plesk/php/5.6/bin/php " . $script_location . " " . $query_string . " &> /dev/null &");

So in your case you can check by replacing /opt/plesk/php/5.6/bin/php-cgi with /opt/plesk/php/5.6/bin/php

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download