PHP | popen( ) Function
The popen() function used to open a pipe to the program specified by the user using the command parameter. It returns a file pointer which is identical to that returned by fopen(), but it is unidirectional in nature i.e it can be only used for reading or writing. The popen() pointer can be used with fgets(), fgetss(), and fwrite(). The file pointer initiated by the popen() function must be closed with pclose().
The command and the mode are sent as parameters to the popen() function and it returns a unidirectional file pointer on success or FALSE on failure.
Syntax:
popen(command, mode)
Parameters Used:
The popen() function in PHP accepts two parameters.
- command : It is a mandatory parameter which specifies the command to be executed.
- mode : It is a mandatory parameter which specifies the connection mode such as read only(r) or write only(w).
Return Value:
It returns a file pointer which is identical to that returned by fopen(), but it is unidirectional in nature.
Errors And Exceptions:
- The file pointer initiated by the popen() function must be closed with pclose().
- If the command to be executed could not be found, then the popen() function returns a valid resource.
Examples:
Input : $my_file= popen("/bin/ls", "r");
Output : 1
Input : $my_file= popen('/executable/gfg.exe', 'r');
echo "'my_file'; " . get_class($my_handle) . "\n";
$file_read = fread($my_file, 4192);
echo $file_read;
pclose($my_file);
Output : 1
Below programs illustrate the popen() function.
Program 1
<?php // opening a pipe $my_file= popen("/bin/ls", "r"); ?> |
Output:
1
Program 2
<?php // opening a pipe $my_file= popen('/executable/gfg.exe', 'r'); // returning name of class of an object using get_class() echo "'$my_file'; " . get_class($my_file) . "\n"; // reading file using fread() $filereader = fread($my_file, 4192); echo $filereader; // closing the pipe pclose($my_file); ?> |
Output:
1
Related Article: PHP | pclose( ) Function
Reference:
http://php.net/manual/en/function.popen.php
Recommended Posts:
- How to call a function that return another function in JavaScript ?
- How to get the function name from within that function using JavaScript ?
- How to get the function name inside a function in PHP ?
- D3.js | d3.map.set() Function
- p5.js | box() Function
- D3.js | d3.min() function
- PHP | max( ) Function
- PHP | Ds\Map get() Function
- CSS | rgb() Function
- PHP | min( ) Function
- D3.js | d3.hcl() Function
- D3.js | d3.rgb() Function
- PHP | dir() Function
- D3.js | d3.lab() Function
- p5.js | value() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



