5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

file_get_contents('php://stdin') で、標準入力を渡さないとどうなるか。

Posted at

ハマったこと

PHPの入出力ストリームラッパーを使って、標準入力を受け取る場合。(手元のPHP7.1で動作確認)
https://www.php.net/manual/ja/wrappers.php.php

たとえばこんなスクリプトで

<?php
$str = file_get_contents('php://stdin');
echo $str;

標準入力を渡すと、その文字列をそのまま表示します。

$ echo 'hoge' | php test.php 
hoge

では、このスクリプトに標準入力を渡さなかった場合どうなるでしょう?

$ php test.php 

空の文字列でも帰ってくるのかなと思ってたのですが。。。
実は、 処理が止まってプロンプトが帰ってきません
(正確には、パイプを渡してない時は標準入力が入力待ちになってブロックされている)

対処策

posix_isatty() 関数を利用します。
http://php.net/manual/ja/function.posix-isatty.php

この関数を使って、 STDINがオープンされていて、 かつ端末に接続されているか否かを判定します。
(標準入力が渡っている場合はfalseになる)

<?php
$str = (posix_isatty(STDIN)) ? 'default' : file_get_contents('php://stdin');
echo $str;

動作検証

$ echo 'hoge' | php test.php 
hoge

$ php test.php 
default
5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?