User Contributed Notes 13 notes

If you plan to use your wrapper in a require_once you need to define stream_stat(). If you plan to allow any other tests like is_file()/is_dir(), you have to define url_stat().

stream_stat() must define the size of the file, or it will never be included. url_stat() must define mode, or is_file()/is_dir()/is_executable(), and any of those functions affected by clearstatcache() simply won't work.

It's not documented, but directories must be a mode like 040777 (octal), and files a mode like 0100666. If you wish the file to be executable, use 7s instead of 6s. The last 3 digits are exactly the same thing as what you pass to chmod. 040000 defines a directory, and 0100000 defines a file. It would be really helpful to add this to the official manual!

The manual says "Reading stops when up to length bytes have been read, [...] or (after opening userspace stream) when 8192 bytes have been read whichever comes first."

I tested it and fread($filehandle, 4096) returns 4096 bytes, so it's working as the manual says it should. You're right when you say "8192 bytes is always passed to stream_read as count", but that doesn't mean fread will return 8192 bytes. If you call fread twice with length 4096, PHP calls stream_read passing 8192 as count on the first fread, and doesn't call it on second fread. On both cases, fread returns the correct amount of bytes.

on using dir_opendir on PHP5 make sure you not return a resource object on success. A resource object is diferent from false but php make a cast to bool to dir_opendir return value and modify the value of your resource to 1.

Use caution with writing code that may use stream wrappers with fread, as fread behaviour is 'inconsistent' with normal file operations because of the 8192 bytes internal buffer used by PHP ( >= 5.0.5 IIRC ).

ie:

fread($filehandle, filesize($filename))

will not work correctly if the file is larger than 8KB, it will only get you the first 8192 bytes. Also, it seems that:

fread($filehandle, 4096)

will still give you 8KB (if the file is larger than 8KB) as 8192 bytes is always passed to stream_read as count.

This makes it somewhat impossible to just 'drop in' a stream where normally a file would be used without taking special care.

Yes, it IS mentioned in the documentation here if you read it really well, but I for one spent some time scratching my head over it, and looking at the bug tracker, I am not the only one. The dev's say this inconsistancy is a feature though, even if it does make stream wrappers pretty much useless 'out of the box'.