PHP Streams

13th December 2019 - 9 minutes read time

Streams are a way of generalising file, network, compression resources and a few other things in a way that allows them to share a common set of features. I stream is a resource object that has streamable behaviour. It can be read or written to in a linear fashion, but not necessarily from the beginning of the stream.

Streams have been available in PHP for quite a while (at least since version 4.3.0) and are used pretty transparently by most PHP programmers. They can be used to access files, network resources, command line arguments, pretty much anything that goes through the input/output stream in PHP.

I was recently looking at ReactPHP and found that the use of streams was a requirement in order to prevent blocking the input/output stream. Although, I had seen streams being used in PHP applications, I wasn't entirely certain how to use them myself. As a result I thought I'd put together a post about them.

Streams come in especially handy when accessing large files. Let's say we needed to access a log file that was a few hundred megabytes in size. We could just read it the file into memory with file_get_contents() and then run through the contents until we find what we need. The problem with this approach is that we would quickly run out of system resources and the program would just error before we had a chance to access the data.

A much better solution to this is to use PHP streams. We can use the function fopen() to get a file handle and then stream the file a little bit at a time, thus reducing the amount of memory needed to read the file.

  1. $handle = fopen('logfile.log', 'r');
  2. while (false !== ($line = fgets($handle))) {
  3. // Do something.
  4. }

This is the transparent stream usage I mentioned above. Whilst we haven't explicitly used any stream functions or syntax we are still using PHP streams to read in chunks of the file.

Stream Syntax

You can access streams directly using the syntax [scheme]://[target]. The scheme is the name of the wrapper and the target is what is being read or written, which largely depends on the thing being read. PHP has a number of different built in wrappers, transports and stream filters. You can find out what they are using the following three functions.

On my current system this outputs this.

  1. Array
  2. (
  3. [0] => tcp
  4. [1] => udp
  5. [2] => unix
  6. [3] => udg
  7. [4] => ssl
  8. [5] => tls
  9. [6] => tlsv1.0
  10. [7] => tlsv1.1
  11. [8] => tlsv1.2
  12. )
  13. Array
  14. (
  15. [0] => https
  16. [1] => ftps
  17. [2] => compress.zlib
  18. [3] => compress.bzip2
  19. [4] => php
  20. [5] => file
  21. [6] => glob
  22. [7] => data
  23. [8] => http
  24. [9] => ftp
  25. [10] => phar
  26. [11] => zip
  27. )
  28. Array
  29. (
  30. [0] => zlib.*
  31. [1] => bzip2.*
  32. [2] => convert.iconv.*
  33. [3] => string.rot13
  34. [4] => string.toupper
  35. [5] => string.tolower
  36. [6] => string.strip_tags
  37. [7] => convert.*
  38. [8] => consumed
  39. [9] => dechunk
  40. )

This gives plenty of options to connect to all sorts of streams.

The php:// Stream

The built in php:// stream is perhaps the most versatile stream wrapper and a good starting point to see how to use streams. An example of the php:// wrapper being used is with the stdin target. This is a read only stream that will read the input from the standard input and create it as a stream in PHP. We can then read the contents of the stream through the fgets() function. This reads one line in at a time, but is fine for what we are doing. We could also use fread() to do this as well.

  1. $stdin = fopen('php://stdin', 'r');
  2. while (false !== ($line = fgets($stdin))) {
  3. echo $line;
  4. }

This script can be used by piping the output of a file into the script on the command line.

cat somelog.log | php stream.php

The output of the script is the contents of the file printed onto the command line, but the core idea of piping into a PHP script is outlined here.

Another example is using php://input to read the input to the script. This is another read only stream that can be used to read the raw body of POST requests to the script. Let's say we called a script with the following curl request.

curl -X POST -d "data1=thing" -d "data2=anotherthing" "http://localhost:8000/stream.php"

We can access the POST data by using the $_POST super-global variable.

print_r($_POST);

This will print out the following.

  1. Array
  2. (
  3. [data1] => thing
  4. [data2] => anotherthing
  5. )

By using php://input we can read out the contents of the POST data directly as an input stream.

  1. $input = fopen('php://input', 'r');
  2. while (false !== ($line = fgets($input))) {
  3. echo $line;
  4. }

This outputs the following.

data1=thing&data2=anotherthing

php://memory and php://temp

PHP 5.1 introduced php://memory and php://temp which allow reading and writing to either memory or a temporary file.

The php://memory can be used in much the same way as the php://input stream, but in this case we can both read and write to it. Here is an example of opening a memory stream and then writing some data to it.

  1. <?php
  2.  
  3. // Open memory stream for reading and writing.
  4. $memoryStream = fopen('php://memory', 'rw+');
  5.  
  6. // Write to the stream.
  7. $text = 'sometext' . time();
  8. fwrite($memoryStream, $text);

No file was created during this code, we are just writing to memory. We can also read from the memory stream as we normally would with files and streams. Note that you can't do this straight away though, we must first rewind the pointer to the start of the stream before we can read the contents of the stream. This can be done using the rewind() function.

  1. // Rewind the stream back to the beginning.
  2. rewind($memoryStream);
  3.  
  4. // Read the data from the stream.
  5. while (false !== ($line = fgets($memoryStream))) {
  6. echo $line;
  7. }

The php://temp stream acts like php://memory, but the crucial difference is that if you write more than a certain amount of data (by default 2MB) then a file is created to store this information. The location of this file depends on your system, but you can find this information out by using the sys_get_temp_dir() function. This file will be automatically deleted when the PHP script ends.

It is also possible to control how much data you can add to the php://temp stream before a file is created. This is done by appending "/maxmemory:n", where 'n' is the maximum amount of data to keep in memory before using a temporary file, in bytes.

  1. // Write to memory, or a file if more than 1028 bytes is written.
  2. $tempStream = fopen('php://temp/maxmemory:1028', 'rw+');

With that in place, if the data we write exceeds more than 1028 bytes then a file is created in the temporary directory.

Streaming A Web Page

You might have seen that http and https are available as stream wrappers. This means that we can open up a web page as a stream resource and stream it in as data. Here is an example of this in action.

  1. $stream = fopen('https://www.hashbangcode.com/', 'r');
  2. echo fread($stream, 50);

This returns the following output.

  1. <!DOCTYPE html>
  2. <html lang="en" dir="ltr" prefix="

Note that we are cutting off the end of the html tag, but this is because we are only reading in the first 50 bytes of data, which is where the data stops.

Filters

Filters are a form of meta-stream that allow you to manipulate data as it passes through a stream. This means you can add filters to function calls like readfile() or fopen() without having to change data before (or after) it passes through the stream. The syntax of filters is php://filter/read=[filter]/resource=[stream] with the filter being from stream_get_filters() above and the stream being any usable stream.

For example, we can expand on the php://stdin example above by passing the input through a filter. In this case we are changing all of the text to be uppercase.

  1. $input = fopen('php://filter/read=string.toupper/resource=php://stdin', 'r');
  2. while (false !== ($line = fgets($input))) {
  3. echo $line;
  4. }

Another example is to swap out the resource part with a web address. This will open the web address as a stream.

$input = fopen('php://filter/read=string.toupper/resource=https://www.hashbangcode.com', 'r');

When we read the contents of the filtered stream it will be in uppercase.

We can do the opposite of this by using the file_put_contents() with a similar filter setup. The snippet below will write the text 'hashbangcode', in uppercase, to a file called uppertext.txt. Note the use of the write filter instead of the read filter.

file_put_contents("php://filter/write=string.toupper/resource=uppertext.txt", "hashbangcode");

Stream Contexts

Another powerful part of streams is creating contexts. This allows us to change the way in which the streams are used. For example, when we use the file_get_contents() function to access a URL it will always do this using a GET request.

echo file_get_contents("https://www.hashbangcode.com");

In order to change the type of request being made we create a stream context and pass this to the function. Stream context are created using the stream_context_create() function, which takes an array that details the context that needs to be created.

The following is an example of creating the needed context to create a POST request (including the content of the request) using stream_context_create() and then using file_get_contents(). I'm using https://postman-echo.com/post/ to test this post request as it will return whatever you sent it and so is a good way of testing that everything worked.

  1. $data = [
  2. 'data1' => 'hello world',
  3. ];
  4.  
  5. [
  6. 'http' => [
  7. 'method' => 'POST',
  8. 'header' => [
  9. 'Accept: application/json',
  10. 'Content-Type: application/x-www-form-urlencoded'
  11. ],
  12. 'content' => http_build_query($data),
  13. ],
  14. ]
  15. );
  16.  
  17. echo file_get_contents("https://postman-echo.com/post/", null, $context);

Running this returns the following.

{"args":{},"data":"","files":{},"form":{"data1":"hello world"},"headers":{"x-forwarded-proto":"https","host":"postman-echo.com","content-length":"17","accept":"application/json","content-type":"application/x-www-form-urlencoded","x-forwarded-port":"443"},"json":{"data1":"hello world"},"url":"https://postman-echo.com/post/"}%

Another good example of using stream contexts is when bypassing the strict SSL rules that PHP has. Let's say we were trying to connect to a local server that doesn't have a fully signed SSL certificate. We can create a stream context that allows the SSL verification step to be bypassed.

  1. [
  2. 'ssl' => [
  3. 'verify_peer' => false,
  4. 'verify_depth' => 5,
  5. 'allow_self_signed' => true,
  6. 'verify_peer_name' => false,
  7. ]
  8. ]
  9. );
  10.  
  11. echo file_get_contents("https://localhost", null, $context);

Conclusion

There are a lot more to streams in PHP than what I have detailed here. PHP includes a bunch of functions that allow you to interact with streams in lots of different ways. It is also possible to create custom stream wrappers and filters, which I might detail in later posts.

Add new comment

The content of this field is kept private and will not be shown publicly.