Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ralphschindler/94a1a51145ff3cc0df2d54b1c5acb9c9 to your computer and use it in GitHub Desktop.
Save ralphschindler/94a1a51145ff3cc0df2d54b1c5acb9c9 to your computer and use it in GitHub Desktop.
PHP Write to stdout via /proc/1/fd/1 using FFI (useful for logging inside a container)
<?php
// php can't write directly to a non-regular-file due to the php filesystem
// abstraction in place. But, we can use direct calls to the low level standard
// library to achieve this.
// normally, you should use the dio extension:
// - https://pecl.php.net/package/dio
// - https://github.com/php/pecl-system-dio/tree/master
// But this is how to achieve it with FFI:
$ffi = FFI::cdef("
int open(const char *pathname, int flags /* mode_t mode */ );
ssize_t write(int fildes, const void *buf, size_t nbyte);
int close(int fildes);
");
$fd = $ffi->open('/proc/1/fd/1', 1);
$string = "Hello " . rand(0, 100) . '!!';
$string .= "\n";
$ffi->write($fd, $string, strlen($string));
$ffi->close($fd);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment