How to check if bash input is being redirect to PHP script? -


i'm writing php script , able optionally use file script input. way:

$ php script.php < file.txt 

i'm, actually, able using file_get_contents:

$data = file_get_contents('php://stdin'); 

however, if don't pass file input, scripts hangs indefinetelly, waiting input.

i tried following, didn't work:

$data = ''; $in = fopen('php://stdin', 'r'); {     $bytes = fread($in, 4096);     // maybe input empty here?! no, it's not :(     if (empty($bytes)) {         break;     }     $data .= $bytes; } while (!feof($in)); 

the script waits fread return value, never returns. guess waits input same way file_get_contents does.

another attempt made replacing do { ... } while loop while { ... }, checking eof before trying read input. didn't work.

any ideas on how can achieve that?

you can set stdin non-blocking via stream_set_blocking() function.

function stdin() {     $stdin = '';     $fh = fopen('php://stdin', 'r');     stream_set_blocking($fh, false);     while (($line = fgets($fh)) !== false) {         $stdin .= $line;     }     return $stdin; }  $stdin = stdin(); // returns contents of stdin or empty string if nothing ready 

obviously, can change use of line-at-a-time fgets() hunk-at-a-time fread() per needs.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -