%ProgramFiles% differences on 64bit Windows

From a command prompt, I get the following:

>echo %ProgramFiles%
C:\Program Files

However, some applications (PHP in this instance, though I've seen the same behavior from within Apache's httpd.conf), it is:

>php -r "echo $_ENV['ProgramFiles'];"
C:\Program Files (x86)

Why is this?

Background: I'm developing scripts that are agnostic of the host OS being 32bit or 64bit, and for configuration files this works great. On a 32bit system, %ProgramFiles% is "C:\Program Files", and on a 64bit system that same %ProgramFiles% seemingly returns C:\Program Files (x86). I'm just curious why the same doesn't hold true when I try it from the Windows command prompt (or in the explorer bar, etc.). Is there a 64bit command prompt or something?


Solution 1:

When a 32-bit application launched in a 64-bit Windows addresses the system environment variables %ProgramFiles% or %commonprogramfiles%, the WoW64 subsystem replaces the values of these variables with the values of the variables %ProgramFiles(x86)% and "%commonprogramfiles(x86)%. Thus, for instance, %ProgramFiles% will be opened as "C:\Program Files (x86)" when addressing from a 32-bit program.

This behavior is determined by the register redirection system that provides backward compatibility of 32-bit software with 64-bit operating systems. The 32-bit environment is emulated for 32-bit programs even despite the fact that the data they are addressing is located in a different place.

To avoid such a redirection in a 32-bit program, you should use the %programfiles% or %COMMONPROGRAMFILES% (i.e. with reverse case) environment variables or the KEY_WOW64_64KEY flag when accessing the corresponding register nodes.