Read from STDIN only if data passed to STDIN

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Read from STDIN only if data passed to STDIN

Post by Ollie Saunders »

I'd like to read from stdin, only if data is present. So that I can make...

Code: Select all

# php myscript.php
...do something different from...

Code: Select all

# cat somefile | php myscript.php
If I use file_get_contents('php://stdin') the shell starts taking input if nothing is piped. I don't seem to be able to use filesize() or anything like that to tell how much data there is without causing the shell to start taking input. fpeek() would probably do the trick, if it existed.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Read from STDIN only if data passed to STDIN

Post by Christopher »

It seem like to you to do the test in the shell:

Code: Select all

if test something ;
then
     php myscript.php
else 
     cat somefile | php myscript.php
fi
(#10850)
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

Hmm I think you misunderstand. I want myscript.php to be able to tell if something has been piped to it or not.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

I looked at the $_SERVER vars and I don't see anything that would give you information where you could determine that. Maybe add an arg or set a shell var?
(#10850)
Post Reply