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";
?>
🙂
More helpful Articles
Tags: Auto, backtick, bad idea, behaviour, browser, code lt, command, command execution, count, default behaviour, dir, Draft, exec, execution, file, fine, function, idea, kind, libphp, line, online, order, performance, performance view, quot, solution, task, way
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 CommentOpera/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