How to find the PHP binary's filename

at 2008-01-07 in General by friebe (0 comments)

In some situations, it can be necessary to find out the filename of the PHP interpreter running the current script from inside this script. Although PHP provides a getmypid() function, it doesn't provide a possibility to query the executable name directly. Continue reading to find out how to get this done for multiple environments.


In general
Programs written in C can use argv[0] which will contain the executable name:
  #include <stdio.h>

int main(int argc, char** argv) {
printf("binary= '%s'\n", argv[0]);
return 0;
}
This will print out binary= './self' (or whatever you typed to execute the command, e.g. if you use a fully qualified path, argv[0] will contain that, and so on).

In PHP, in contrast, $argv[0] contains the PHP script that is running (e.g. "self.php" or "-" if standard input / "-r" command line option contents are evaluated).

The "_" environment entry
On a bash shell to a Un*x system, we can use query the environment for the entry consisting of a single underscore:
  edit:~# php -r 'var_dump(getenv("_"));'
string(12) "/usr/bin/php"
On a Cygwin shell for example, this is also possible:
  $ php -r 'var_dump(getenv("_"));'
string(41) "/cygdrive/c/Programme/php-5.2.5-Win32/php"
The latter though is not really the executable's name, and surely not what Windows-PHP can handle, so we'd have to transform it to Windows-form (c:\Programme\php-5.2.5-Win32\php.exe) first.

From what I read on Google (and there isn't much on this topic) this method does not seem to be quite reliable. This forum thread in the Java forums suggests to use dladdr() (which, of course, is not exposed in PHP userland).

The /proc filesystem
On some Linux systems, one can find information about the current process in the files in /proc/[PID]/, where PID may be self to query the current process:
  edit:~# php -r 'var_dump(readlink("/proc/self/exe"));'
string(13) "/usr/bin/php5"
This does not work on - for example - FreeBSD though - it does not have a /proc filesystem mounted by default.


Windows management
On Windows systems, we can use the following COM queries against the Windows Management API:
<?php 
$wmi= new Com('winmgmts:');
$exe= $wmi->get('//./root/cimv2:Win32_Process.Handle="'.getmypid().'"')->executablePath;
?>


Solution
Because this is quite a hassle to do, we'll create an API to the PHP runtime in a new RFC - probably something like:
<?php 
$exe= Runtime::getInstance()->getExecutable()->getFileName();
?>

...will solve the problem in the future.



Subscribe

You can subscribe to the XP framework's news by using RSS syndication.


Categories

News
General
PHP5
Announcements
RFCs
Further reading
Examples
Editorial
EASC
Experiments
Unittests
Databases

Related

Find related articles by a search for «How».