0

I am onUbuntu 14.04, with PHP 5.5.9. There, I have a very simple file a.php:

<?php

$a = exec('clear');
print($a);

If I run the script as is now I get:

$ php a.php 
<screen cleared> # nothing is displayed in the screen
                 # "clear" was performed successfully

However, if I comment the print($a) to just have a file like this:

<?php

$a = exec('clear');

then nothing happens:

$ php a.php 
$               # nothing happened, I see the previous line above

To my understanding, it is the call to the variable $a what makes clear to be performed. But it doesn't make much sense, since exec() docs says:

exec — Execute an external program

Is there a reason why clear doesn't get performed until print() is called?

Note this is related to the question Clear CMD-shell with php but I am asking here why this happens.

braX
  • 11,506
  • 5
  • 20
  • 33
fedorqui
  • 275,237
  • 103
  • 548
  • 598

1 Answers1

2

Actually, clear gets executed when calling exec. You just don't see its action on the screen until you actually output it.

Adrian Roman
  • 534
  • 4
  • 8
  • But the action of `clear` is to clear the screen, why should I wait for its action to "happen" until a `print` happens? – fedorqui Apr 19 '16 at 07:05
  • 1
    clear simply outputs a couple of escape sequences. In your case, the output goes into $a. The terminal does not get cleared until you send that to it by printing it. – Adrian Roman Apr 19 '16 at 07:15
  • @fedorqui, in console do `clear | od -t x1`. As Adrian says, on *NIX systems, the console is controlled by the control codes. (See for example `man console_codes` on Linux). The computer where `clear` runs is not necessary the same where the console is. And it is not necessary a real console. The console codes form a protocol which allows application to control console regardless where it is or how it is implemented. – Dummy00001 Apr 19 '16 at 09:35
  • @Dummy00001 ok. So `clear` provides some control codes (33c, for example) that, together, clear the screen. Printing them effectively performs the action. – fedorqui Apr 19 '16 at 11:03
  • @fedorqui, precisely. `man terminfo` (or `man termcap` for older *nix systems; but also easier to read than terminfo man) for more information about where from the console codes come from. After than `man ncurses` for how to access the terminal capabilities database. – Dummy00001 Apr 19 '16 at 11:09