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.
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;
?>Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
