PHP Custom Stream Wrappers

24th December 2019

Part of the strength of PHP's stream wrappers is the ability to add our own stream wrappers to the list of available wrappers. We can therefore natively open any type of resource just by registering a stream wrapper and then using the normal fopen() functions.

The custom stream wrapper functionality is made possible through a few functions built into PHP.

stream_get_wrappers()

The first of these is functions is stream_get_wrappers(), which returns an array of the stream wrappers available on our system. Here is an example of this in use.

  1. php -r "print_r(stream_get_wrappers());"
  2. Array
  3. (
  4. [0] => https
  5. [1] => ftps
  6. [2] => compress.zlib
  7. [3] => compress.bzip2
  8. [4] => php
  9. [5] => file
  10. [6] => glob
  11. [7] => data
  12. [8] => http
  13. [9] => ftp
  14. [10] => phar
  15. [11] => zip
  16. )

We can use any of these stream types to create resources and then work with them.

stream_wrapper_unregister()

We can unregister any of the existing streams by using the stream_wrapper_unregister() function. Using this function we can actually break PHP by removing the ability to open http addresses as streams. The following code checks for the existence of the http stream, and then removes it.

  1. $wrapperExists = in_array("http", stream_get_wrappers());
  2. if ($wrapperExists) {
  3. }

Now, if we try to use the http stream through the fopen() function like this.

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

We get the following error.

PHP Warning:  fopen(): Unable to find the wrapper "http" - did you forget to enable it when you configured PHP?

This doesn't seem inherently useful, but it will come in handy when adding our own custom stream wrappers.

stream_wrapper_register()

Finally, we have the stream_wrapper_register(), with which we can register a custom stream swapper class. First though, we need to create a class that we can register as a stream wrapper. This class needs to implement a few core methods. The very minimum class you need to create should implement the following interface.

  1. interface StreamWrapper {
  2. /**
  3.   * This method is called immediately after the wrapper is initialized (f.e. by fopen() and file_get_contents()).
  4.   *
  5.   * @param string $path
  6.   * Specifies the URL that was passed to the original function.
  7.   * @param string $mode
  8.   * The mode used to open the file, as detailed for fopen().
  9.   * @param int $options
  10.   * Holds additional flags set by the streams API. It can hold one or more of the following
  11.   * values OR'd together.
  12.   * @param string $opened_path
  13.   * If the path is opened successfully, and STREAM_USE_PATH is set in options, opened_path
  14.   * should be set to the full path of the file/resource that was actually opened.
  15.   *
  16.   * @return bool
  17.   * Returns TRUE on success or FALSE on failure.
  18.   */
  19. public function stream_open(string $path, string $mode, int $options, string $opened_path = NULL): bool;
  20.  
  21. /**
  22.   * This method is called in response to fclose().
  23.   *
  24.   * No value is returned.
  25.   */
  26. public function stream_close(): void;
  27.  
  28. /**
  29.   * This method is called in response to fread() and fgets().
  30.   *
  31.   * @param int $count
  32.   * How many bytes of data from the current position should be returned.
  33.   *
  34.   * @return string
  35.   * If there are less than count bytes available, return as many as are available. If no
  36.   * more data is available, return either FALSE or an empty string.
  37.   */
  38. public function stream_read(int $count): string;
  39.  
  40. /**
  41.   * This method is called in response to feof().
  42.   *
  43.   * @return bool
  44.   * Should return TRUE if the read/write position is at the end of the stream and if no
  45.   * more data is available to be read, or FALSE otherwise.
  46.   */
  47. public function stream_eof(): bool;
  48.  
  49. /**
  50.   * Seeks to specific location in a stream.
  51.   *
  52.   * @param int $offset
  53.   * The stream offset to seek to.
  54.   * @param int $whence
  55.   * Possible values:
  56.   * - SEEK_SET - Set position equal to offset bytes.
  57.   * - SEEK_CUR - Set position to current location plus offset.
  58.   * - SEEK_END - Set position to end-of-file plus offset.
  59.   *
  60.   * @return bool
  61.   * Return TRUE if the position was updated, FALSE otherwise.
  62.   */
  63. public function stream_seek(int $offset, int $whence = SEEK_SET): bool;
  64.  
  65. /**
  66.   * Retrieve information about a file resource.
  67.   *
  68.   * @return array
  69.   * See stat().
  70.   */
  71. public function stream_stat(): array;
  72. }

There are a few other methods available in this class. For a full list see the PHP documentation on the stream wrapper class.

With that interface we can create a simple class.

There were a few ideas that came to mind when thinking about what kind of stream wrapper class to create. Since we removed the ability to use the http stream in the last example, I thought it would be a good idea to add back in a mock http stream class.

The following class implements the StreamWrapper interface in order to create a mock http wrapper. All this class does is return a very simple html string when read. Note that the stream_read() method does more than just return a string. It will return a string the first time around and then return a blank string every time after this. The PHP documentation for stream_read() states that some functions (like file_get_contents()) will continuously loop and call stream_read() until it receives an empty string so I have added some logic to handle this.

  1. class MockHttpStreamWrapper implements StreamWrapper
  2. {
  3. protected $streamRead;
  4.  
  5. public function stream_open(string $path, string $mode, int $options, string $opened_path = NULL): bool
  6. {
  7. // Imagine that we open a stream here.
  8. return true;
  9. }
  10.  
  11. public function stream_close(): void
  12. {
  13. // Imagine the stream being closed here.
  14. }
  15.  
  16. public function stream_read(int $count): string
  17. {
  18. if ($this->streamRead == true) {
  19. // If we have read the stream then return a string.
  20. return '';
  21. }
  22.  
  23. // Set the fact that we have read the stream.
  24. $this->streamRead = true;
  25.  
  26. // Return a HTML string.
  27. return '<body><p>Hello World</p></body>';
  28. }
  29.  
  30. public function stream_eof(): bool
  31. {
  32. // Always return true.
  33. return true;
  34. }
  35.  
  36. function stream_seek(int $offset, int $whence = SEEK_SET): bool
  37. {
  38. return false;
  39. }
  40.  
  41. public function stream_stat(): array
  42. {
  43. return [];
  44. }
  45. }

This class can then be used as a http stream wrapper by using the stream_wrapper_register() function.

stream_wrapper_register('http', 'MockHttpStreamWrapper', STREAM_IS_URL);

We pass in 'http' as the stream type and the class name MockHttpStreamWrapper as the class we defined above. The third parameter is any additional flags, which should be set to STREAM_IS_URL if protocol is a URL protocol (which we are setting here). The default here is 0, which is a local stream.

Note that we first need to unregister the http stream wrapper before we can register our own one or PHP will throw an error.

  1. $existed = in_array("http", stream_get_wrappers());
  2. if ($existed) {
  3. // Unregister the http stream wrapper.
  4. }
  5.  
  6. // Register our custom stream wrapper.
  7. stream_wrapper_register('http', 'MockHttpStreamWrapper', STREAM_IS_URL);
  8.  
  9. // Use the new custom stream wrapper.
  10. $stream = fopen('http://www.example.com/', 'r');
  11. while (false !== ($line = fgets($stream))) {
  12. echo $line;
  13. }
  14. fclose($stream);

This code outputs the following.

<body><p>Hello World</p></body>%

This doesn't seem that useful at face value. However, what we have done here in intercept any communication through http using fopen() or file_get_contents(). This is useful if you are using fopen() to interact with an API and want to create a mock for testing purposes.

There are a few examples out there that show this method being used to interface with gluster file systems, S3 resources and all sorts of different ways of interacting with data. Stream wrappers are used in Drupal 8 to provide an interface to the public and private file systems. This means that we can use fopen('public://file.txt') to open a file in the public file directory without having to get the developer to include a bunch of boiler plate code to translate the scheme to a location.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.