2

As discussed here for PHP, we can redirect stdout to text file. I'm looking for similar way to redirect stdin to file too.

Though, my google search and search on our site results with little helpful. We can easily do that in Python as discussed here

Nam G VU
  • 33,193
  • 69
  • 233
  • 372
  • 1
    You can not do it from the PHP script itself as it won't be aware about the way that standard input was derived anyways (cli? sapi? who knows). But why fight the windmill? Just use the the [standard way to work with STDIN](https://stackoverflow.com/a/4475622/2637490) and redirect input stream at the script call, like `php in.php < in.txt` – Alma Do Dec 12 '17 at 11:38
  • @AlmaDo The reason why is that we don't have access to php execution e.g. I'm practicing PHP on hackerrank.com and all in/out are from stdin/stdout which we cannot change that. – Nam G VU Dec 12 '17 at 11:40
  • Then.. obey the constraints? I'm sure they're there for a reason (and I would imagine that if program does not consume standard input / does not produce standard output - it won't be counted as a "working example" since that could be detected). Or for practicing ground - set up a local environment and play around all you want. – Alma Do Dec 12 '17 at 11:42
  • @AlmaDo My practicing ground setup is that I add some preceding code to do the redirecting to file for in/out - every thing else to be as-is with stdin/stdout read+write method calls – Nam G VU Dec 12 '17 at 11:47

1 Answers1

1

Not sure if this is what you want... but you can read stdin like this:

$stdin = fopen('php://stdin', 'r');
$input = trim(fgets($stdin));
fclose($stdin);
file_put_contents('filename',$input);
Nam G VU
  • 33,193
  • 69
  • 233
  • 372
Khazul
  • 179
  • 6
  • 1
    What I'm looking for is some `configuration PHP code` that turns your `fgets($stdin)` to read from some chosen file instead of stdin. – Nam G VU Dec 12 '17 at 12:05