zerocaffe.in Blog of Uncaffeinated Experiences on Entrepreneurship and Everything Else

4Oct/082

Linux commands output in PHP

My friend Rahul was giving me a demo of their Web UI and a small but nifty feature caught my eye. They had a feature of being able to configure their systems using the Web UI (which is pretty cool in itself!) and the console output from the configuration command in turn would be displayed in a html iFrame. My company has a similar internal tool which does the same but then showing the output in a step-by-step manner would really be a huge help.

Anyways, so cooked up a quick php function for our system. Hope someone finds this snippet useful.

< ?php
/**
 * @func: Executes the command passed to it as argument and prints the
 * command console output line by line onto the html output stream hence
 * giving the illusion of having the command executing in the html window itself.
 */
function html_exec_cmd($cmd)	{
	$proc = popen("($cmd)2>&1", "r");
	echo '<pre>';
	while(!feof($proc))	{
		$result = fgets($proc, 100);
		echo htmlspecialchars($result);
		flush();
	}
	pclose($proc);
	echo '</pre>';
}

html_exec_cmd('wget yahoo.com'); # sample command.
?>