Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php

What is the popen() function in PHP?

Muhammad Ashir

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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(), and fwrite() with the popen() pointer

The file pointer initiated by the popen() function must be closed with pclose().

Syntax

popen(string $command, string $mode): resource|false

Parameters

  • command: command specifies which command is to be executed.
  • mode: mode defines whether the pipe is read-only (r) or write-only (w).

Return value

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.

Code

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);
?>

RELATED TAGS

php

CONTRIBUTOR

Muhammad Ashir
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring