Troubleshooting PHP’s exec() or shell_exec() on Windows

So you’re trying to get some random program to work when you run exec() or shell_exec() via PHP in Windows; it works when you run it from the command line, but not when you run the same exact script via the web. Maybe it even returns an elusive 255 retval error code.

The first thing you should do is check file/folder permissions, and use utility commands like whoami, dir, and path to make sure things are sane. Also check if any settings (like cd, or set VARIABLE) are staying across multiple commands; usually they don’t, and you need to string them together && like && this or put them all in a batch file. But if all that doesn’t work, try this.

The last bit of environment to check when running something in Windows is, well, ALL THE ENVIRONMENT VARIABLES. There’s a lot of them. You can see them by running:
set
and likewise change them with:
set VARIABLE=value
In order to get my script working, I had to run set via the command line from the user I wanted it to run as (usually your WWW or Inet user) — after testing that the command actually worked from the command line, of course. Then I ran shell_exec(“set”) via the web and compared the outputs. There were a few missing or different environment variables, like HOMEPATH, TEMP, and APPDATA. Once I made them all match (a batch script helped for some reason) it worked like a charm.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s