Current Location: Home> Latest Articles> pclose and popen: How to Use Them Together? A Basic Practical Example

pclose and popen: How to Use Them Together? A Basic Practical Example

gitbox 2025-09-12
<span><span><span class="hljs-meta">&lt;?php</span></span><span>
</span><span><span class="hljs-comment">// The following snippet is unrelated to the main article and can serve as a preliminary example</span></span><span>
</span><span><span class="hljs-keyword">echo</span></span><span> </span><span><span class="hljs-string">"This is a preliminary content example\n"</span></span><span>;
</span><span><span class="hljs-variable">$time</span></span><span> = </span><span><span class="hljs-title function_ invoke__">date</span></span><span>(</span><span><span class="hljs-string">"Y-m-d H:i:s"</span></span><span>);
</span><span><span class="hljs-keyword">echo</span></span><span> </span><span><span class="hljs-string">"Current time: <span class="hljs-subst">$time</span></span></span><span>\n";
</span><span><span class="hljs-meta">?&gt;</span></span><span>
<p><hr></p>
<p></span><?php<br>
/*<br>
Title: [pclose and popen: How to Use Them Together? A Basic Practical Example]<br>
*/</p>
<p>echo "In PHP, the popen() and pclose() functions are commonly used to execute system commands and capture their output. Below, we illustrate their usage with a simple, practical example.\n\n";</p>
<p>// 1. Open a process using popen<br>
// 'r' mode indicates we will read the command's output<br>
$handle = popen("ls -l", "r"); // On Windows, you can change this to 'dir'<br>
</span>if (!$handle) {<br>
die("Unable to open process\n");<br>
}</p>
<p>// 2. Read the command output<br>
echo "Command output:\n";<br>
while (!feof($handle)) {<br>
$line = fgets($handle);<br>
if ($line !== false) {<br>
echo $line;<br>
}<br>
}</p>
<p>// 3. Close the process using pclose and get the return value<br>
$return_value = pclose($handle);<br>
echo \nProcess return value: $return_value\n";</p>
<p>/*<br>
Explanation:</p>
<ol data-is-last-node="" data-is-only-node="">
<li>
<p>popen() launches a child process to execute the specified command and returns a file handle.</p>
</li>
<li>
<p>You can read the child process's output line by line using fgets() or fread().</p>
</li>
<li>
<p>After reading, pclose() must be used to close the handle and obtain the command's exit status.</p>
</li>
<li data-is-last-node="">
<p data-is-last-node="">The 'r' mode is for reading output, while 'w' mode is for sending input to the process.<br>
This combination is ideal for scenarios where real-time command output is needed.<br>
*/<br>
?><br>
</span>