Execute external program with PHP and arguments - php

I wish to run external program with PHP and provide some arguments, like:
exec('C:\\Program Files\\iNFekt\\infekt\\infekt-cmd.exe -S --utf-16 '.$nfoFile, $output, $return_var);
But nothing happens, $output is empty array, $return_var is 1
What is my mistake here ?

Use shell_exec to get the output:
$output = shell_exec('C:\\Program Files\\iNFekt\\infekt\\infekt-cmd.exe -S --utf-16 '.$nfoFile');
From the Manual:
shell_exec — Execute command via shell and return the complete output as a string

Related

PHP exec returns empty string while executing Python script

I am trying to run a Python script inside PHP and show the output.
I tried with simple test.py inside PHP, which print hello world without problem. But when I try to execute my desired command from PHP script the exec() returns empty string instead of output.
So the here is my php script. Below snippets works fine:
$output = exec("python test.py");
var_dump($output);
But not the desired one.
$command = "python -m scripts.label_image --graph=tf_files/retrained_graph.pb --image=".$uploadfile;
$output = exec($command);
var_dump($output);
so the folder structure is:
/var/www/mysite/
-scripts(folder which contains python scripts)
-tf_files(folder with other files)
-uploads (image folder)
Can someone tell me what is going wrong?
Sample output in stdout/shell:
the variable $output should an argument.
If you do this, you should get only the last output of your script.
exec("python test.py", $output);
var_dump($output);
https://www.php.net/manual/en/function.exec.php

Assign awk to variables in php

I have the following code in place. It provides the information needed, however I would like to assign the output to variables.
$cmd = "ssh machine 'cat /usr/local/reports/file.dat | awk -F'[[:space:]][[:space:]][[:space:]]*' '{print \"<tr><td>\"$2\"</td><td>\"$3\"</td></tr>\"}'";
system($cmd);
This correctly runs and produces a table with the 2nd and 3rd columns from the file. However, I would now like to assign the columns to variables for each line read in the file.
Any ideas?
system always outputs the command output directly. You could use output buffering to capture it, but you should use shell_exec instead:
$result = shell_exec( $cmd );
Few suggestions:
Use heredoc to make reader friendly
avoid cat /usr/local/reports/file, awk can read file directly, there is no need of using cat command
if you want take care of return status use exec() function.
shell_exec() returns all of the output stream as a string. exec returns the last line of the output by default, but can provide all output as an array specifed as the second parameter.
Here is code snippet
<?php
$cmd =<<<EOF
ssh user#host "awk -F'[[:space:]][[:space:]][[:space:]]*' '{
print \"<tr><td>\" $2 \"</td><td>\" $3 \"</td></tr>\"
}
' /usr/local/reports/file.dat 2>&1"
EOF;
/*
execute command in 1st argument,
save output in array in 2nd argument
store status in 3rd argument
*/
exec($cmd, $out, $return);
if($return==0)
{
print_r($out);
/* your case you can just
echo implode(PHP_EOL, $out);
*/
}else{
/* Failed to execute command
do some error handling */
die( 'Failed to execute command : '. $cmd );
}
?>

Passing arguments from PHP to a remote shell script

I am executing a shell script located on a remote machine from a PHP script. So, let's say that PHP script runs on A and shell script runs on B (10.0.0.37).
I have the following code which runs well
$cmd = "ssh 10.0.0.37 /usr/tmp/script.sh";
exec($cmd, $output);
Now, I want to pass arguments to the shell script, preferably in JSON format.
The output of echo json_encode($arg) is as follows:
[{"original_name":"pdf_convert","changed_name":"pdf_convert_1"},{"original_name":"video_encode","changed_name":"video_encode_1"},{"original_name":"video_transcode","changed_name":"video_transcode_1"}]
I want to pass this as an argument to the shell script. So,
$data = json_encode($data);
$cmd = "ssh 10.0.0.37 /usr/tmp/script.sh $data";
exec($cmd, $output);
However, I see that the argument is not correctly read by the shell script. I tried putting single quotes around $data, didn't work. Also, tried using escapeshellarg($data), still did not work.
Edit
The output of echo escapeshellarg($data) is
'[{"original_name":"pdf_convert","changed_name":"pdf_convert_1"},{"original_name":"video_encode","changed_name":"video_encode_1"},{"original_name":"video_transcode","changed_name":"video_transcode_1"}]'
Also, if there is any other format which can be parsed easily in a shell script, then I would lie to use that format (not necessarily JSON). I see that I may have to use 'jq' to parse json which needs me to install an additional package.
Bash isn't very good at accepting a JSON string in as arguments...
One way to get around bash trying to parse the arguments is for your php script to write the JSON string to a file, and for the bash script to parse that file with jq
I was able to use serilaize to send the json data. Below is the code.
$data = json_encode($arg)
$data = escapeshellarg($data);
$data = serialize($data);
$data = str_replace('"','\"',$data);
$cmd = "ssh 10.0.0.37 /usr/tmp/script.sh $data";
I can now get the data in the shell script.
PHP:
<?php
$json = '[{"original_name":"pdf_convert","changed_name":"pdf_convert_1"},{"original_name":"video_encode","changed_name":"video_encode_1"},{"original_name":"video_transcode","changed_name":"video_transcode_1"}]';
$cmd = $json;
$cmd = addslashes($cmd);
// addslashes does not escapes curly braces
$cmd = strtr($cmd, array('{' => '\\{', '}' => '\\}'));
$cmd = escapeshellarg($cmd);
$cmd = "ssh localhost echo $cmd";
echo "\n$cmd\n\n";
exec($cmd, $output);
var_dump($output)
Shell (/tmp/1.sh):
#!/bin/sh
echo "$1"
Shell Output:
ssh localhost /tmp/1.sh '[\{\"original_name\":\"pdf_convert\",\"changed_name\":\"pdf_convert_1\"\},\{\"original_name\":\"video_encode\",\"changed_name\":\"video_encode_1\"\},\{\"original_name\":\"video_transcode\",\"changed_name\":\"video_transcode_1\"\}]'
array(1) {
[0]=>
string(200) "[{"original_name":"pdf_convert","changed_name":"pdf_convert_1"},{"original_name":"video_encode","changed_name":"video_encode_1"},{"original_name":"video_transcode","changed_name":"video_transcode_1"}]"
}

how to prevent system() function from printing output in the browser?

I'm using system() PHP function to run some curl commands like this system("curl command here",$output); but it displays results on screen. Any way to avoid this output?
You're using the wrong function for that. According to the docs:
system() is just like the C version of the function in that it executes the given command and outputs the result.
So it always outputs. Use exec­Docs instead which does return (and not output) the programs output:
$last = exec("curl command here", $output, $status);
$output = implode("\n", $output);
Or (just for completeness) use output buffering­Docs:
ob_start();
system("curl command here", $status);
$output = ob_get_clean();
You coud try using output buffering.
ob_start();
system("curl command here",$output);
$result = ob_get_contents();
ob_end_clean();
You could either modify the command string and append " 1>/dev/null 2>&1" or - more elegantly - execute the process with a pipe (see example #2).
For a more refined control over the process' file handles, you can also use proc_open().
The system function displays the output from your command, so you're out of luck there.
What you want is to change system for exec. That function will not display the command's output.
No, you should use PHP curl library

svnlook through php gives one line

I have a simple php exec command that calls svnlook. If I run the command through the terminal I get all the output I expect. If I run it as shown below, I only get the last item.
$list = exec("svnlook changed -r ".$urlCleaned." ".$SVNEXPORT);
echo $list;
Can I buffer the output? If so how? And will that help?
That's by design and is explained:
string exec ( string $command [, array &$output [, int &$return_var ]] )
Return Values
The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.
To get the output of the executed command, be sure to set and use the output parameter.
http://php.net/manual/en/function.exec.php
exec("svnlook changed -r ".$urlCleaned." ".$SVNEXPORT, $output);
var_dump($output);
Alternatively, shell_exec returns everything.

Categories