SoFunction
Updated on 2025-03-10

Issues that need to be paid attention to when using the crc32 function of php (or it is a pitfall)

A few days ago, I wrote a subtable program, and the hash algorithm used is crc32. The functions of subtable are as follows:

Copy the codeThe code is as follows:

    function _getHash($username)
    {
        $hash = crc32($username) % 512;
        return $hash;
    }

    function _getTable($username)
    {
        $hash = self::_getHash($username);
        return 'user_' . $hash;
    }
 


First, generate the data on the local 32-bit window machine and insert it into the corresponding table. However, the program and data were uploaded to the server (64 is Linux), and the data was found to be unavailable. After troubleshooting, it was found that the result of crc32 on the server was different from that on the local area. After checking the php manual again, I found that the interface of Crc32 was originally related to the machine.
Description of php manual:
Copy the codeThe code is as follows:

Because PHP's integer type is signed many crc32 checksums will result in negative integers on 32bit platforms. On 64bit installations all crc32() results will be positive integers though.

The result returned by crc32 will overflow on a 32-bit machine, so the result may be negative. And it won't overflow on 64-bit machines, so it's always the right one.

The CRC algorithm is calculated by word length bit.

The crc32 function will be calculated according to the two constant references in PHP_INT_SIZE, PHP_INT_MAX
The definition of these two constants:
The word length of an integer number is related to the platform, although the maximum is usually about two billion (32-bit signed). PHP does not support unsigned integers. The word length of the Integer value can be represented by the constant PHP_INT_SIZE. Since PHP 4.4.0 and PHP 5.0.5, the maximum value can be represented by the constant PHP_INT_MAX.
PHP_INT_SIZE: 4, PHP_INT_MAX: 2147483647 in the 32 bits output
PHP_INT_SIZE: 8, PHP_INT_MAX: 9223372036854775807 in the output