Assign awk to variables in php - 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 );
}
?>

Related

Why does lscpu have a different output in a php script than in the command line? [duplicate]

My awk command works as expected and returns 2 lines at command prompt.
When I use php "exec" function, it returns only the second line.
echo exec("awk -v RS=\",\" '/some_text/' test1.html");
How do I return all output of shell command using PHP?
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.
Returns false on failure.
To get the output of the executed command, be sure to set and use the output parameter.
It only returns the last line of output so use:
output
If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as \n, is not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().
http://php.net/manual/en/function.exec.php
exec("awk -v RS=\",\" '/some_text/' test1.html", $out);
foreach($out as $line) {
echo $line;
}
Though this question is answered, I'm posting this alternate solution for more options.
This solution replaces line-breaks directly on shell using shell tr command, and pipes through the one-line result.
Also php's exec command requires a second argument for assigning the shell output, while shell_exec can be used directly to declare or output the result of shell execution.
Updating above example, to replace line-breaks \n with a blank space, which could be any other string, however, cannot be empty.
echo shell_exec("awk -v RS=\",\" '/some_text/' test1.html | tr '\n' ' '");
To simply remove all line-breaks without replacements using the -d flag of tr command,
echo shell_exec("awk -v RS=\",\" '/some_text/' test1.html | tr -d '\n'");

Execute external program with PHP and arguments

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

AWK pipe output from TTY to PHP

I have a tty device (/dev/ttyUSB0), which occasionally outputs a string in the form of Cycle 1: 30662 ms, 117.41 W. I'm using a simple bash script to process it:
#!/bin/sh
stty -F /dev/ttyUSB0 57600
cd /home/pi
while true; do
cat /dev/ttyUSB0 | awk '{ print $0 > "/dev/stderr"; if (/^Cycle/) { print "update kWh.rrd N:" $5 } }' | php5 test.php
sleep 1
done
The test.php script looks like this:
<?php
stream_set_blocking(STDIN, 0);
$line = trim(fgets(STDIN));
$file = 'kwhoutput.txt';
$current = file_get_contents($file);
$current .= $line;
file_put_contents($file, $current);
?>
however, the kwhoutput.txt remains empty. Why is this not working?
awk is buffering your data. Use fflush() to flush the buffers after each output line:
awk '{
print $0 > "/dev/stderr";
if (/^Cycle/) {
print "update kWh.rrd N:" $5;
fflush();
}
}' < /dev/ttyUSB0 | php5 test.php
Also make sure that /dev/ttyUSB0 actually outputs a line (terminated by \n), and not just a string of data.
You should also fix up your php script to:
Read multiple lines and append them one by one (otherwise, the script will skip every other line).
Find out how to append to a file in php. Reading the whole file, concatenating a string in memory, then writing the whole file is not the way to go.

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

exec function not returning all rows

My awk command works as expected and returns 2 lines at command prompt.
When I use php "exec" function, it returns only the second line.
echo exec("awk -v RS=\",\" '/some_text/' test1.html");
How do I return all output of shell command using PHP?
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.
Returns false on failure.
To get the output of the executed command, be sure to set and use the output parameter.
It only returns the last line of output so use:
output
If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as \n, is not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().
http://php.net/manual/en/function.exec.php
exec("awk -v RS=\",\" '/some_text/' test1.html", $out);
foreach($out as $line) {
echo $line;
}
Though this question is answered, I'm posting this alternate solution for more options.
This solution replaces line-breaks directly on shell using shell tr command, and pipes through the one-line result.
Also php's exec command requires a second argument for assigning the shell output, while shell_exec can be used directly to declare or output the result of shell execution.
Updating above example, to replace line-breaks \n with a blank space, which could be any other string, however, cannot be empty.
echo shell_exec("awk -v RS=\",\" '/some_text/' test1.html | tr '\n' ' '");
To simply remove all line-breaks without replacements using the -d flag of tr command,
echo shell_exec("awk -v RS=\",\" '/some_text/' test1.html | tr -d '\n'");

Categories