How can I get the current PHP executable from within a script?

It is worth noting that now in PHP 5.4+ you can use the predefined constant PHP_BINARY:

PHP_BINARY

Specifies the PHP binary path during script execution. Available since PHP 5.4.


Update; nowadays PHP_BINARY works with XAMPP as well (Tested with XAMPP that comes with PHP 7.4).


Old Answer

Unfortunately PHP_BINARY is returning the httpd binary (on Windows XAMPP), so I'm back to using paths...

    if (defined('PHP_BINARY') &&
                PHP_BINARY &&
                in_array(PHP_SAPI, array('cli', 'cli-server')) &&
                is_file(PHP_BINARY)) {

          return PHP_BINARY;
    } else if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        $paths = explode(PATH_SEPARATOR, getenv('PATH'));
        foreach ($paths as $path) {
            if (substr($path, strlen($path)-1) == DIRECTORY_SEPARATOR) {
                $path = substr($path, 0, strlen($path)-1);
            }
            if (substr($path, strlen($path) - strlen('php')) == 'php') {
                $response = $path.DIRECTORY_SEPARATOR . 'php.exe';
                if (is_file($response)) {
                    return $response;
                }
            } else if (substr($path, strlen($path) - strlen('php.exe')) == 'php.exe') {
                if (is_file($response)) {
                    return $response;
                }
            }
        }
    } else {
        $paths = explode(PATH_SEPARATOR, getenv('PATH'));
        foreach ($paths as $path) {
            if (substr($path, strlen($path)-1) == DIRECTORY_SEPARATOR) {
                $path = substr($path, strlen($path)-1);
            }
            if (substr($path, strlen($path) - strlen('php')) == 'php') {
                if (is_file($path)) {
                    return $path;
                }
                $response = $path.DIRECTORY_SEPARATOR . 'php';
                if (is_file($response)) {
                    return $response;
                }
            }
        }
    }
    return null;

On my server I've PHP 5.3.14.

I've found a predefined constant: PHP_BIN_DIR

Then, supposing the file name of the executable file is always 'php', $php_cmd = PHP_BIN_DIR.'/php' points to my PHP executable file.

Tags:

Php