Replacing PHP http Wrapper¶
<?php
// based on Alexandre Daubois code
// Refactored to make it running here
class MockHttp
{
private string $data = '';
private int $pos = 0;
public $context;
public function stream_open(
string $path,
string $mode,
int $options,
?string &$opened_path = null
): bool {
$this->data = json_encode([
'mocked' => true,
'url' => $path,
]);
$this->pos = 0;
return true;
}
public function stream_read(int $count): string
{
$result = substr($this->data, $this->pos, $count);
$this->pos += strlen($result);
return $result;
}
public function stream_eof(): bool
{
return $this->pos >= strlen($this->data);
}
public function stream_stat(): array
{
return [
'size' => strlen($this->data),
];
}
// Required when using STREAM_IS_URL in modern PHP versions
public function url_stat(string $path, int $flags): array|false
{
return [
'size' => strlen($this->data),
];
}
}
stream_wrapper_unregister('http');
stream_wrapper_register('http', MockHttp::class, STREAM_IS_URL);
$data = file_get_contents('http://api.example.com/users');
var_dump($data);
stream_wrapper_restore('http');
Did you know you can override built-in protocols such as https://?
You can create mocks! I’d advise to use dedicated tools such as #Symfony MockHttpClient. But in the case of vanilla PHP…
I’ll let you tell me if it’s a good or a terrible idea 😉.
See Also¶
http wrapper renewed [Try me]
PHP Features¶
Last updated: 14 July 2026