Checking if your code is running on 64-bit PHP

后端 未结 5 1234
梦如初夏
梦如初夏 2020-11-29 05:09

Does anyone know of a way of checking within PHP if the script is running as either 32-bit or 64-bit? Currently I\'m using PHP 5.3.5.

Ideally I\'d like to write a f

相关标签:
5条回答
  • 2020-11-29 05:26

    You could write a function like this:

    function is_32bit(){
      return PHP_INT_SIZE === 4;
    }
    

    Then you could use the sample code you posted:

    if ( is_32bit() ) {
        do_32bit_workaround();
    } else {
        do_everything_else();
    }
    
    0 讨论(0)
  • 2020-11-29 05:34

    I just looked around and didn't find anything too promising. There's a good chance that you can use $_SERVER['SERVER_SOFTWARE'] to tell (check out what it prints on your system), but making this portable and always accurate is probably not doable.

    0 讨论(0)
  • 2020-11-29 05:39

    Check the PHP_INT_SIZE constant. It'll vary based on the size of the register (i.e. 32-bit vs 64-bit).

    In 32-bit systems PHP_INT_SIZE should be 4, for 64-bit it should be 8.

    See http://php.net/manual/language.types.integer.php for more details.

    0 讨论(0)
  • 2020-11-29 05:46

    A short way to get the number of bits.

        strlen(decbin(~0));
    

    How this works:

    The bitwise complement operator, the tilde, ~, flips every bit.

    @see http://php.net/manual/en/language.operators.bitwise.php

    Using this on 0 switches on every bit for an integer.

    This gives you the largest number that your PHP install can handle.

    Then using decbin() will give you a string representation of this number in its binary form

    @see http://php.net/manual/en/function.decbin.php

    and strlen will give you the count of bits.

    Here is it in a usable function

    function is32Bits() {
        return strlen(decbin(~0)) == 32;
    }
    
    0 讨论(0)
  • 2020-11-29 05:47

    Here is an example that can be used from console

    For Windows:

    php -r "echo (PHP_INT_SIZE == 4 ? '32 bit' : '64 bit').PHP_EOL;" && php -i | findstr Thread
    

    For Linux

    php -r "echo (PHP_INT_SIZE == 4 ? '32 bit' : '64 bit').PHP_EOL;" && php -i | grep Thread
    

    Output example:

    64 bit
    Thread Safety => disabled
    
    0 讨论(0)
提交回复
热议问题