CHAPTER 9 – FILES AND STREAMS – Input/Output Streams

With PHP, you can use stdin, stdout, and stderr as files. These "files," linked with the stdin, stdout, and stderr stream of the PHP process, can be accessed by using a protocol specifier in the call to fopen(). For the program input and output streams, this specifier is php://. This feature is most useful when work- ing with the Command Line Interface (CLI), which is explained in more detail in Chapter 16, "PHP Shell Scripting." Two more IO streams are available: php://input and php://output. With php://input, you can read raw POST data. You may want to do so when you need to process WebDAV requests or obtain data from the POST requests yourself, which can be useful when working with WebDAV, XML-RPC, or SOAP. The following example shows how to obtain form data from a form that has two fields with the same name: form.html: <html> <form method="POST" action="process.php"> <input type="text" name="example"> <select name="example"> <option value="1">Example line 1</option> <option value="2">Example line 2</option> </select> <input type="submit"> </form> </html>

process.php: <h1>Dumping $_POST</h1> <?php var_dump ($_POST); ?> <h1>Dumping php://input</h1> <?php $in = fopen ("php://input", "rb"); while (!feof($in)) { echo fread ($in, 128); } ?> The first script contains only HTML code for a form. The form has two elements with the name "example": a text field and a select list. When you sub- mit the form by clicking the submit query button, the script process.php runs and displays the output shown in Figure 9.1. Fig. 9.1 php://input representation of POST data As you can see, only one element--the selected value from the select list-- is displayed when you dump the $_POST array. However, the data from both fields shows up in the php://input stream. You can parse this raw data yourself. Although, raw data might not be particularly useful with simple POST data, it's useful to process WebDAV requests or to process requests initiated by other applications. The php://output stream can be used to write to PHP's output buffers, which is essentially the same as using echo or print(). php://stdin and php:// input are read-only; php://stdout, php://stderr, and php://output are write-only.

Post Comment
Login to post comments