Frage

I have a php script which is run in the terminal and it returns a number the number is human-friendly formated so :

php script.php

will for example output: 1 020 536

But sometimes we need this script to output the number as a computer-friendly version so in my case :

1020536

Is it possible to detect directly from the php script if it's called directly or in the following ways :

echo $(php script.php)

and

php script.php | cat

The both version should output the number non formated.

Is that possible ?

Thanks in advance !

War es hilfreich?

Lösung

You can do that with posix-isatty. Here is an example;

in your script.php you can implement;

<?php

if ( !posix_isatty(STDOUT) ) {
    fwrite(STDOUT, "You piped this script to another command");
    exit(2);
}
fwrite(STDOUT, "Called directly");

exit(0);

?>

Update: Just for the incomers:

posix_isatty helps you to detect if script output piped to elsewhere or not. In case above, posix_isatty(STDOUT) means, your php script outputs to terminal. If you pipe your php script like php script | cat, posix_isatty(STDOUT) will be false. Because, you have redirected output of your script to cat as input. In other words, you redirected your script output to place that is not an terminal.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top