The popen() function in PHP is used to open a pipe to a process using the command parameter. It returns a file pointer similar to fopen(); however, the file pointer returned by popen() is unidirectional, meaning it can only be used to read or write.
You can use
fgets(),fgetss(), andfwrite()with thepopen()pointer
The file pointer initiated by the popen() function must be closed with pclose().
popen(string $command, string $mode): resource|false
command: command specifies which command is to be executed.mode: mode defines whether the pipe is read-only (r) or write-only (w).popen returns a file pointer that is identical to that returned by fopen(), but it is unidirectional in nature.
Note: If the command to be executed cannot be found, a valid resource is returned. This allows you to access any error message returned by the shell.
The following code exemplifies the use of popen(). We provide the path to the executable of the shell ls command as the command parameter. The path to all the binary executables of shell commands resides in the /bin folder in Linux and other UNIX-like operating systems.
We set the mode to r, which signifies that we want to read from the pipe.
Lastly, we read from the pipe using the fread() function, just as we would for a file, and store it in the $read variable. We then close the pipe using the pclose call.
<?php$handle = popen("/bin/ls", "r");$read = fread($handle, 2096);print_r("$handle: ".gettype($handle)."\n$read \n");pclose($handle);?>
Free Resources