Using PHP Execution Functions: exec, system, passthru, popen, proc_open, and shell_exec

This article demonstrates how to use PHP's execution functions—exec, system, passthru, popen, proc_open, and shell_exec—to run shell commands, capture output, and handle process streams, providing example code snippets for each function in PHP scripts.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using PHP Execution Functions: exec, system, passthru, popen, proc_open, and shell_exec

1. exec function

<?php
  $test = "ls /tmp/test";   // ls is the Linux command to list directory contents
  exec($test,$array);       // execute command
  print_r($array);
?>

2. system function

<?php
  $test = "ls /tmp/test";
  $last = system($test);
  print "last: $last
";
?>

3. passthru function

<?php
  $test = "ls /tmp/test";
  passthru($test);
?>

4. popen function

<?php
  $test = "ls /tmp/test";
  $fp = popen($test, "r");  // open a process pipe
  while (!feof($fp)) {      // read from the pipe
    $out = fgets($fp, 4096);
    echo $out;         // output the data
  }
  pclose($fp);
?>

5. proc_open function

<?php
  $test = "ls /tmp/test";
  $descriptors = array(
    array("pipe", "r"),   // stdin
    array("pipe", "w"),   // stdout
    array("pipe", "w")    // stderr
  );
  $fp = proc_open($test, $descriptors, $pipes);   // open a process with pipes
  echo stream_get_contents($pipes[1]);    // read stdout (index 1)
  proc_close($fp);
?>

6. proc_open function (duplicate example)

<?php
  $test = "ls /tmp/test";
  $descriptors = array(
    array("pipe", "r"),   // stdin
    array("pipe", "w"),   // stdout
    array("pipe", "w")    // stderr
  );
  $fp = proc_open($test, $descriptors, $pipes);   // open a process with pipes
  echo stream_get_contents($pipes[1]);    // read stdout (index 1)
  proc_close($fp);
?>

7. shell_exec function

<?php
  $test = "ls /tmp/test";
  $out = shell_exec($test);
  echo $out;
?>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendexecCommand Executionproc_openSystem
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.