Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Symfony Command that read file from file name or STDIN
namespace AmceBundle\Command;
class MyCommand
// ...
protected function execute(InputInterface $input, OutputInterface $output)
if ($filename = $input->getArgument('filename')) {
$contents = file_get_contents($filename);
} else if (0 === ftell(STDIN)) {
$contents = '';
while (!feof(STDIN)) {
$contents .= fread(STDIN, 1024);
} else {
throw new \RuntimeException("Please provide a filename or pipe template content to STDIN.");
// Do whatever you want with `$contents`
Copy link

chalasr commented Jun 21, 2016

This line should be removed:

- $filename = $input->getArgument('filename');

Thanks for sharing this.

Copy link

Cosmologist commented Jul 12, 2017

Or use stream_get_contents

Copy link

sroze commented Oct 3, 2017

@chalasr removed 😉

Copy link

courtney-miles commented Nov 17, 2019

I found that the strategy of using ftell() to identify if there was content to get from STDIN was problematic when running PHPUnit via PHPStorm because ftell() always returned 0. I'm not sure what PHPStorm is doing with STDIN for this to happen.

So I found the following alternative strategy from PHP - detect STDIO input - Stack Overflow by dedee which appears to work in all cases.

$readStreams = [STDIN];
$writeStreams = [];
$exceptStreams = [];
$streamCount = stream_select($readStreams, $writeStreams, $exceptStreams, 0);

$hasStdIn = $streamCount === 1;

if ($hasStdIn) {
    // Read content from STDIN ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment