Last active
May 6, 2024 20:33
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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