55

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 function so my code can look like this:

if( is_32bit() === true ) {
    do_32bit_workaround();
}
do_everything_else();

Anyone have any thoughts?

hakre
  • 193,403
  • 52
  • 435
  • 836
binarycleric
  • 703
  • 1
  • 5
  • 7

4 Answers4

105

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.

Radon8472
  • 4,285
  • 1
  • 33
  • 41
coreyward
  • 77,547
  • 20
  • 137
  • 166
  • 27
    @matb33 ...it's the same answer with a switch statement...? – coreyward Sep 14 '12 at 15:01
  • 1
    The problem with this is that it doesn't say what the value of `PHP_INT_SIZE` should be for 32-bit vs. 64-bit. matb33's link provides that information. – Nathan Jones Jul 09 '14 at 17:58
  • This was useful for me: http://stackoverflow.com/questions/16510636/php-convert-string-into-float-double – louisav Feb 28 '17 at 21:30
  • 7
    Quick command line check: `php -r 'echo (PHP_INT_SIZE===8)?"64 bit ":"32 bit ";'` – Micah Oct 30 '18 at 16:21
  • `phpinfo()` tells me I am on x64 architecture, but `PHP_INT_SIZE` gives me `4` and the Chris0 method gives me `32`. Do you have any idea? – Master DJon May 31 '22 at 23:16
13

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();
}
Tim Penner
  • 3,551
  • 21
  • 36
13

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
naT erraT
  • 502
  • 1
  • 5
  • 19
8

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;
}
Chris0
  • 475
  • 5
  • 6