PHP Function Reference

PHP popen() Function



The PHP popen() function opens a pipe to a process executed by forking the command given by command parameter. The function returns a file pointer identical to that returned by fopen(), except that it is unidirectional (may only be used for reading or writing) and must be closed with pclose(). This pointer may be used with fgets(), fgetss(), and fwrite(). When the mode is 'r', the returned file pointer equals to the STDOUT of the command, when the mode is 'w', the returned file pointer equals to the STDIN of the command.

Syntax

popen(command, mode)

Parameters

command Required. Specify the command to execute.
mode

Required. Specify the connection mode. It can be either 'r' for reading, or 'w' for writing.

On Windows, popen() defaults to text mode, i.e. any \n characters written to or read from the pipe will be translated to \r\n. If this is not desired, binary mode can be enforced by setting mode to 'rb' and 'wb', respectively.

Return Value

Returns an unidirectional file pointer identical to that returned by fopen(), except that it is unidirectional (may only be used for reading or writing). If an error occurs, returns false.

Example: popen() example

The example below shows how to use this function to open a pipe to a process executed by forking given command.

<?php
//opening a pipe
$handle = popen("/bin/ls", "r");

//some code to be executed

//closing the pipe
pclose($handle);
?>

Please note that if the command to be executed could not be found, a valid resource is returned.

Example: popen() example

Consider one more example which demonstrates the usage of this function.

<?php
error_reporting(E_ALL);

//opening a pipe
$handle = popen('/path/to/executable 2>&1', 'r');

echo "'$handle'; " . gettype($handle) . "\n";
$read = fread($handle, 2096);
echo $read;

//closing the pipe
pclose($handle);
?>

❮ PHP Filesystem Reference