Opening Pipes to and from Processes Using popen()

In Chapter 11, “Working with Files and Directories,” you learned how to open a file for reading and writing, using the fopen() function. Now, you'll see that you can open a pipe to a process using the popen() function.

The popen() function is used like this:

$file_pointer = popen("some command", mode)

The mode is either r (read) or w (write).

Listing 12.1 is designed to produce an error—it will attempt to open a file for reading, which does not exist.

Listing 12.1. Using popen() to Read a File
1: <?php
2: $file_handle = popen("/path/to/fakefile 2>&1", "r");
3: $read = fread($file_handle, 2096);
4: echo $read;
5: pclose($file_handle);
6: ?>

Line 2 utilizes the popen() function, attempting ...

Get Sams Teach Yourself PHP, MySQL® and Apache All in One now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.