4

Possible Duplicate:
Can PHP detect if its run from a cron job or from the command line?

I'm trying to determine whether or not the STDOUT resource on a PHP command-line script is being piped to another command or not, in order to appropriately display tabular data (if output is direct to terminal, it looks good to have table cells wrapped in +-----+ borders; but not if trying to inspect that data with awk or another command.)

Afte finding this answer, I've tried inspecting the STDOUT resource with stream_get_meta_data() and all of the other functions I can find in the PHP manual which operate on streams, but in every case, the resource looks exactly the same whether it is being piped to another process or not.

Is there any way to find this out in PHP?

Community
  • 1
  • 1
goldenapples
  • 386
  • 1
  • 15
  • possible duplicate of [Can PHP detect if its run from a cron job or from the command line?](http://stackoverflow.com/questions/190759/can-php-detect-if-its-run-from-a-cron-job-or-from-the-command-line) and http://stackoverflow.com/questions/11327367/detect-if-a-php-script-is-being-run-interactively-or-not or http://stackoverflow.com/questions/3648863/detect-if-stdin-is-a-tty-device-terminal-or-pipe-in-php – mario Sep 10 '12 at 23:34

1 Answers1

5

You can use posix_isatty assuming you have the POSIX extension (you probably do):

posix_isatty(STDOUT)

If it's true, then you are not outputting to a pipe. isatty is a common method for doing this in C programs and others.

Note that this doesn't check that it's output to a pipe specifically, just whether it's output to an interactive terminal (a pipe is not one).

goldenapples
  • 386
  • 1
  • 15
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • This worked! Its not exactly what I want, as I would still like to include some graphical elements in the script output if, for example, the output is being redirected to a file. But it allows at least some rough-grain control over the script output. – goldenapples Sep 10 '12 at 23:24