Use PHP's Stream Wrappers for Custom Protocols

Use PHP's Stream Wrappers for Custom Protocols

Implement custom stream wrappers to handle special file systems or protocols in a transparent way to the rest of your application.

class CustomWrapper
{
    private $position;
    private $data;

    public function stream_open($path, $mode, $options, &$opened_path)
    {
        $url = parse_url($path);
        $this->data = "This is data from {$url['host']}";
        $this->position = 0;
        return true;
    }

    public function stream_read($count)
    {
        $ret = substr($this->data, $this->position, $count);
        $this->position += strlen($ret);
        return $ret;
    }

    public function stream_eof()
    {
        return $this->position >= strlen($this->data);
    }
}

stream_wrapper_register("custom", CustomWrapper::class);

// Usage
$contents = file_get_contents("custom://example.com");
echo $contents; // Outputs: This is data from example.com
← Back to Tips List