Question

I'm trying to start vncviewer on Raspberry Pi using PHP, where RPi is the client and my VNC server runs MS Windows.

In PHP I'm using this script to start the vncviewer

$cmd="echo password | vncviewer -autopass " .$ip;
shell_exec($cmd);

It works when I only run the shell script from RPi, but when try it from PHP I get this error:

Error: Can't open display:

Is there any workaround for this error ?

Was it helpful?

Solution

If you're using X11, you probably need to set your DISPLAY variable.

X11 clients (programs) that need to open windows on an X11 server (display) use this variable to determine where the client should find the server. The client/server model is used here because the server provides window display capabilities to the client.

X includes the ability to display windows on remote servers across a network, though 99.9% of the time you'll be displaying things on the main display on the machine running the program, so usually, DISPLAY=localhost:0.0.

The catch is that if DISPLAY is not set, a program doesn't know where to open its windows, even if there's an X server running on the same machine. And when programs are run by cron or the system startup scripts or in fact anything that was not launched by X itself (including a PHP script run by your web server), they usually don't have DISPLAY set to anything.

So .. as you noted in comments, setting DISPLAY=:0 will tell vncviewer where to send its windows. This is a shortform of DISPLAY=localhost:0.0. The hostname, if excluded, is assumed to be localhost. And the .0 at the end refers to the screen number, which also defaults to zero. Check out the X documentation for more details.

And as you've also noted in comments, in the environment where X is running (i.e. DISPLAY is already set), you may need to run xhost + to allow programs not launched by X to open windows.

To set an environment variable in PHP, use something like:

putenv("DISPLAY=:0");

before the code that launches VNC.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top