Petr Bečka Petr Bečka - 4 years ago 377
Bash Question

unable to execute shell_exec() with variable

I'm trying to run shell_exec() with variable passed with AJAX from client.

This code causes error (input file doesn't exist!):

$searched_image = escapeshellarg("/home/XXX/XXX/XXX/XXX/XXX/sp_dom1.jpg");
$old_path = getcwd();
chdir('../elevation/source_code/altitudes_system/');
$altitudes_system_result = shell_exec('./predict_altitude.sh -i "{$searched_image}" -p basic -o 0');
chdir($old_path);


But when I replace "{$searched_image}" in shell_exec(...) with /home/XXX/XXX/XXX/XXX/XXX/sp_dom1.jpg code works well:

$old_path = getcwd();
chdir('../elevation/source_code/altitudes_system/');
$altitudes_system_result = shell_exec('./predict_altitude.sh -i /home/XXX/XXX/XXX/XXX/XXX/sp_dom1.jpg -p basic -o 0');
chdir($old_path);


Don't you have any idea why it works like this?

Answer Source

You write:

'./predict_altitude.sh -i "{$searched_image}" -p basic -o 0'

Inside single-quoted strings variables are not evaluated.

You can use this, instead:

"./predict_altitude.sh -i '{$searched_image}' -p basic -o 0"

Or - to avoid unpredictable evaluations - this:

$cmd = './predict_altitude.sh -i \''.$searched_image.'\' -p basic -o 0';
shell_exec( $cmd );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download