11-consume-stdin.php 727 B

1234567891011121314151617181920212223242526
  1. <?php
  2. use React\EventLoop\Loop;
  3. require __DIR__ . '/../vendor/autoload.php';
  4. if (!defined('STDIN') || stream_set_blocking(STDIN, false) !== true) {
  5. fwrite(STDERR, 'ERROR: Unable to set STDIN non-blocking (not CLI or Windows?)' . PHP_EOL);
  6. exit(1);
  7. }
  8. // read everything from STDIN and report number of bytes
  9. // for illustration purposes only, should use react/stream instead
  10. Loop::addReadStream(STDIN, function ($stream) {
  11. $chunk = fread($stream, 64 * 1024);
  12. // reading nothing means we reached EOF
  13. if ($chunk === '') {
  14. Loop::removeReadStream($stream);
  15. stream_set_blocking($stream, true);
  16. fclose($stream);
  17. return;
  18. }
  19. echo strlen($chunk) . ' bytes' . PHP_EOL;
  20. });