PHP system(); hide command output - How to hide
displayed output with exec();
I've recently wanted to
use PHP's embedded system(""); -
external command execute function in order to use
ls + wc to
calculate the number of files stored in a directory. I know many
would argue, this is not a good practice and from a performance
view point it is absolutely bad idea. However as I was lazy to code
ti in PHP, I used the below line of code to do the task:
<?
echo "Hello, ";
$line_count = system("ls -1 /dir/|wc -l");
echo "File count in /dir is $line_count \n";
?>
This example worked fine for me to calculate the number of files in
my
/dir, but unfortunately the execution output was also
visialized in the browser. It seems this is some kind of default
behaviour in both libphp and php cli. I didn't liked the behaviour
so I checked online for a solution to prevent the system(); from
printing its output.
What I found as a recommendations on many pages is instead of
system(); to prevent command execution output one should use
exec();.
Therefore I used instead of my above code:
<?
echo "Hello, ";
$line_count = exec("ls -1 /dir/|wc -l");
echo "File count in /dir is $line_count \n";
?>
By the way insetad of using exec();, it is also possible to just
use
` (backtick) - in same way like in bash scripting's
``.
Hence the above code can be also written for short like this:
<?
echo "Hello, ";
$line_count = `ls -1 /dir/|wc -l`;
echo "File count in /dir is $line_count \n";
?>
:)