PHP system(); hide command output – How to hide displayed output with exec();

Saturday, 7th April 2012

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";
?>

🙂

Share this on:

Download PDFDownload PDF

Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

2 Responses to “PHP system(); hide command output – How to hide displayed output with exec();”

  1. Hipolito Smallwood says:
    Google Chrome 4.0.221.7 Google Chrome 4.0.221.7 Windows 7 Windows 7
    Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.2 (KHTML, like Gecko) Chrome/4.0.221.7 Safari/532.2

    I just found your site from google and I like your site, keep up the great work.

    View CommentView Comment
    • admin says:
      Opera 11.00 Opera 11.00 GNU/Linux x64 GNU/Linux x64
      Opera/9.80 (X11; Linux x86_64; U; bg) Presto/2.7.62 Version/11.00

      Something I forgot to mention is CLOC tool also works on Windows. Program developers in Windows projects can benefit from it in Project development.

      View CommentView Comment

Leave a Reply

CommentLuv badge