1

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 !

8
  • couldn't you use a parameter to define weather it should be formated human or machine friendly? That would make the bahaviour of said script more predictable. Which is a good thing if it comes to scripts isn't it? Contrary to movies and books? ;D Commented Apr 29, 2014 at 13:17
  • I could but I would really prefer to do it the way I asked ^^ Commented Apr 29, 2014 at 13:19
  • please upload your php file Commented Apr 29, 2014 at 13:19
  • you could add an init set to just that file. i.e. ini_set('memory_limit','1GB'); Commented Apr 29, 2014 at 13:21
  • 1
    @MyWetSocks you can do that with posix_isatty. See my answer for further detail Commented Apr 29, 2014 at 13:33

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you tell me what this function do ?..i didnt get anything from the manual
@CodeLover I have updated my answer for further detail. If you have any other questions, do not hesitate to ask. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.