Secret Name
Secret Name

Reputation: 41

PHP Raspberry Pi system() echo prints

I have little problem. When I type in PHP on my Raspberry Pi machine this:

system("echo hello");

It prints to the web page. Why? Why it doesn't print into terminal?

I didn't see it on my PuTTY.

Thank you very much.

Upvotes: 0

Views: 1397

Answers (3)

Sebi
Sebi

Reputation: 1436

There is no problem with system. This function returns whatever the executed program printed to stdout. In this case it is "hello".

Using wall to print to everyone

As Jasen suggested, you could use wall to print it to everyone using the system. This is useful if you don't know the number of the tty, but it displays a banner to the terminal if you don't run it as root.

system("echo test | wall");

Manually printing to the terminal

To print manually, without the banner and root, you can add your apache server user to tty group, like so: (replace the user)

sudo usermod -a -G tty WEB_SERVER_USER

Then you could do something along those lines:

system("your command > /dev/pts/0");

or

$output = system("your command");
file_put_contents('/dev/pts/0', $output);

That of course assumes that your terminal is mapped to /dev/pts/0. ls /dev/pts/ to see the list.

Redirecting stderr

In addition to the above, if your program outputs to stderr, you need to attach 2>&1 at the end of your command, for example:

system("your_command 2>&1 | wall");

This will redirect both streams.

Running your script in the terminal

You can also run your script in terminal, using php-cli. To install cli, use:

sudo apt-get install php5-cli

Then, in your script, you can use echo system("your_command 2>&1"); and run it in the terminal:

php script.php

Upvotes: 1

E. Celis
E. Celis

Reputation: 727

The system function does not executes the command in any attached tty, that is why don't see any output on the tty attached to your Putty session.

If you want to send commands to your GPIO pins in the Pi through PHP you can use the system function to do things like system("echo 1 > /sys/class/gpio/xyz) but be aware that php must be run with root privileges which isn't not by default in the Apache websever.

Upvotes: 0

Jasen
Jasen

Reputation: 12402

this is beacuse in a web context stdout is the result returned to the browser

if you want to write to terminals of logged in users

$wall=popen("wall","w");
fwrite($wall,"Hello!\n");
pclose($wall);

they must have "mesg" turned on. (I think on is the default)

the command mesg y will turn it on, man mesg for more info.

Upvotes: 0

Related Questions