Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - detect STDIO input

Tags:

php

stdio

What I want is being able to optionally pipe STDIO to a PHP script. If not, it'll take input from a file instead. So sometimes I'll simply run the script, other times I'll do something like

grep text logfile | php parseLog.php

I have a loop very much like this and it works fine when STDIO exists:

while (FALSE !== ($line = fgets(STDIN)))
{
        $customLogArr[]=$line;
}

When there's no STDIO though it halts waiting for some, it doesn't even enter the loop.

What I'd like to do is be able to detect if I have STDIO input or not. Is there a way to do that?

like image 702
Arkandel Avatar asked Feb 17 '15 21:02

Arkandel


2 Answers

if(FALSE !== ftell(STDIN))
{
    while (FALSE !== ($line = fgets(STDIN)))
    {
        $customLogArr[]=$line;
    }
}

For STDIN, if nothing can be read, ftell() will return false.

like image 167
grant sun Avatar answered Nov 10 '22 00:11

grant sun


Is this what you're looking for? Forgive me if I misunderstood, this should not hold you when there's no input on STDIN.

stream_set_blocking(STDIN, 1);

function CheckSTDIN() {
    $read = array(STDIN);
    $wrte = NULL;
    $expt = NULL;
    $a = stream_select($read, $wrte, $expt, 0);
    if ($a && in_array(STDIN, $read)) {
        // you can read from STDIN now, it'll only be available if there is anything in STDIN
        // you can return the value or pass it to global or class variable
        return fread(STDIN, 255); // set your desired string length
    } else return false;
}

while (FALSE !== ($line = CheckSTDIN())) {
        $customLogArr[]=$line;
}
like image 30
DeDee Avatar answered Nov 09 '22 23:11

DeDee