14

I have a command, for example 'git diff' that output a colorized result when I run it from the terminal.

Now, I want to call that command from a CLI php script and display in the console the colorized result. I have try with exec(), system(), passthru() but in all case the output has been converted to plain black and white text.

Is there a way to preserve the color of the standard result? If not, does someone know why this information get lost?

3
  • Just an idea: it's probably environment-variable related. A quick test might provide clues: env > env_a.out && php -r 'system("env");' > env_b.out && diff env_a.out env_b.out Commented Apr 13, 2012 at 20:58
  • I try your test, once both env file reordered, the diff is only like this: 'SHLVL=1 against SHLVL=2' Commented Apr 13, 2012 at 21:10
  • 1
    That similar? I'm surprised to be honest. Perhaps providing further detail about your environment would be helpful in your question, as well as simplifying the problem by trying to output a color yourself first (php -r 'printf("%c[32mGreen%c[0m\n", 27, 27);') rather than from invoking a command like git. Commented Apr 13, 2012 at 21:29

1 Answer 1

10

In all likelihood the command you are running is checking to see if output is to a terminal and not colorizing it if it isn't. There is usually a way to force it, but that's going to be specific to the command itself; in the case of git diff, you can specify --color=always.

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

2 Comments

Yes, your are right, if I did something like that: <?php system('git diff --color=always'); ?> I got the color. So the question now is: Is there a way, from php, to tell the commands that yes, we are in a terminal?
Unfortunately, the command really isn't attached to a terminal the way PHP executes it (unlike the way the shell does). Even when you use passthru, PHP places itself in between the command and the terminal; it just doesn't modify the output as it passes through. It's not just colors; full-screen commands will simply not work at all when run this way. So short of some elaborate pseudo-terminal setup, which I don't think you can do from PHP anyway, I don't think there's a general solution.

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.