Juno_okyo

Execute shell commands in PHP

Jan 27th, 2015
413
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.20 KB | None | 0 0
  1. <?php // Source: http://www.binarytides.com/execute-shell-commands-php/
  2.  
  3. /**
  4.     Method to execute a command in the terminal
  5.     Uses :
  6.      
  7.     1. system
  8.     2. passthru
  9.     3. exec
  10.     4. shell_exec
  11.  
  12. */
  13. function terminal($command)
  14. {
  15.     //system
  16.     if(function_exists('system'))
  17.     {
  18.         ob_start();
  19.         system($command , $return_var);
  20.         $output = ob_get_contents();
  21.         ob_end_clean();
  22.     }
  23.     //passthru
  24.     else if(function_exists('passthru'))
  25.     {
  26.         ob_start();
  27.         passthru($command , $return_var);
  28.         $output = ob_get_contents();
  29.         ob_end_clean();
  30.     }
  31.      
  32.     //exec
  33.     else if(function_exists('exec'))
  34.     {
  35.         exec($command , $output , $return_var);
  36.         $output = implode("n" , $output);
  37.     }
  38.      
  39.     //shell_exec
  40.     else if(function_exists('shell_exec'))
  41.     {
  42.         $output = shell_exec($command) ;
  43.     }
  44.      
  45.     else
  46.     {
  47.         $output = 'Command execution not possible on this system';
  48.         $return_var = 1;
  49.     }
  50.      
  51.     return array('output' => $output , 'status' => $return_var);
  52. }
  53.  
  54. $o = terminal('ls');
  55. if($status == 0)
  56. {
  57.     echo $o['output'];
  58. }
  59. else
  60. {
  61.     //some problem
  62. }
Add Comment
Please, Sign In to add comment