| Categories | Latest | Search | Login |

Back

system and popen



You can easily run system commands in php using either 'system' or 'popen'.

Using the system command provides little control and basically dumps the raw output.


system('ls -al');

Most programs will not usually output a html formatted response, resulting in it all being on a single line.

You could capture the data using the output control functions such as 'ob_start', 'ob_get_contents' and 'ob_end_clean'. They basically redirect the output stream and allow us to capture it in a variable. We then change all the new line symbols into html br tags using the 'nl2br' function.


function exe($cmd)
{
   ob_start();
   system($cmd);
   $l = ob_get_contents();
   ob_end_clean();
   $l = nl2br($l);
   return $l;
}

print exe('ls -al');



Personally I prefer to use popen. Here's an example to show it in action. I've written the 'popen' handling into a function which returns the outputted response as an array.


function exe($cmd){
   $aret=array();
   if(!$f=popen($cmd,'r')){return null;}
   while(!feof($f)){
      $o=fgets($f,1024);
      $aret[]=$o;
   }
   pclose($f);
   return $aret;
}

$a=exe('ls -al');
foreach($a as $e){
   print $e."<br />";
}



Back

rabbit By rabbit Created on 24th of June 2010, at 10.55 am
Category: PHP: File IO

rabbitin on again!

Other Docs by rabbit

   system and popen
   Ticker Tape Scrollers
   Javascript Regular Expressions
   Simple Popup Dialogues
   Matrix

View all



Digg  del.icio.us  Reddit  Slashdot  StumbleUpon  TwitThis  


COMMENTS


Search Docs


Browse Docs

Programming
     C
     C++
     Python
     Tcl/Tk
     Java
     PHP
     Perl
     HTML
     Javascript
     Other
Computing
     Linux
     Windows
     Security
     Networks
     Graphics
     Gaming
     Other