Can PHP tell if the server os is 64-bit?

后端 未结 12 577
北荒
北荒 2020-12-09 08:52

I am dealing with Windows here.

I know you can use the $_SERVER[\'HTTP_USER_AGENT\'] variable to detect the OS of the browser viewing the page, but is t

12条回答
  •  眼角桃花
    2020-12-09 09:12

    Looking into all of this answers and some other solutions + my idea to "ask computer directly" i get this universal solution:

    function is_64bit()
    {
        // Let's ask system directly
        if(function_exists('shell_exec'))
        {
    
            if (in_array(strtoupper(substr(PHP_OS, 0, 3)), array('WIN'), true) !== false || defined('DIRECTORY_SEPARATOR') && '\\' === DIRECTORY_SEPARATOR)
            {
                // Is Windows OS
                $shell = shell_exec('wmic os get osarchitecture');
                if(!empty($shell))
                {
                    if(strpos($shell, '64') !== false)
                        return true;
                }
            }
            else
            {
                // Let's check some UNIX approach if is possible
                $shell = shell_exec('uname -m');
                if(!empty($shell))
                {
                    if(strpos($shell, '64') !== false)
                        return true;
                }
            }
        }
    
        // Check is PHP 64bit (PHP 64bit only running on Windows 64bit version)
        if (version_compare(PHP_VERSION, '5.0.5') >= 0)
        {
            if(defined('PHP_INT_SIZE') && PHP_INT_SIZE === 8)
                return true;
        }
    
        // bit-shifting can help also if PHP_INT_SIZE fail
        if((bool)((1<<32)-1))
            return true;
    
        // Let's play with bits again but on different way
        if(strlen(decbin(~0)) == 64)
            return true;
    
        // Let's do something more worse but can work if all above fail
        // The largest integer supported in 64 bit systems is 9223372036854775807. (https://en.wikipedia.org/wiki/9,223,372,036,854,775,807)
        $int = '9223372036854775807';
        if (intval($int) == $int)
            return true;
    
        return false;
    }
    

    Is tested on various machines and for now I have positive results. Fell free to use if you see any purpose.

提交回复
热议问题