PHP Reference ยท String Functions
PHP crc32() function
Reference for PHP crc32(): compute a CRC-32 checksum as an integer, convert it to hex with dechex() or sprintf(), compare with hash('crc32b') and limits.
crc32() calculates the 32-bit cyclic redundancy check of a string and returns it as an integer. CRC-32 is an error-detecting checksum: it is quick and good at spotting accidental changes such as a flipped bit in a download, but it is not a cryptographic hash, and it is trivial to forge a different input with the same value.
Because the value is an unsigned 32-bit number, it is always positive on 64-bit PHP. Convert it to the familiar eight-digit hex form with dechex() or sprintf("%08x").
<?php echo crc32("hello"); // 907060870 echo sprintf("%08x", crc32("hello")); // 3610a686
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
crc32(string $string): int
| Name | Description |
|---|---|
$string |
The data to checksum. |
Return value: the CRC-32 checksum as an integer between 0 and 4,294,967,295 on 64-bit systems. On 32-bit builds the integer can be negative, so format it with %u or sprintf("%u").
Usage notes
- Use it for error detection and simple bucketing, not for security, passwords or identifying data. The space of 4 billion values collides quickly in large sets.
- Hex form:
sprintf("%08x", crc32($s)). Plaindechex()drops leading zeros, so pad when comparing with other tools. hash("crc32b", $s)returns the same checksum as hex. The algorithm namedcrc32inhash()is a different (bzip2-style) variant; there is alsocrc32c(Castagnoli).- Files: use
hash_file("crc32b", $path); PHP has nocrc32_file(). - Compatibility with other languages: the value matches the CRC-32 used by zip, gzip and PNG, so it agrees with the same checksum computed in most other languages.
- For bigger or safer needs use
hash()withsha256, orxxh3for fast non-cryptographic hashing.
Related
hash(),md5()andsha1(),dechex(),sprintf()- Lessons: String functions, Math functions