Skip to content

crc32()

The crc32() function is used to calculate a cyclic redundancy check (CRC) of a string. The syntax of the crc32() function is as follows:

The PHP syntax of the crc32()

php
int crc32 ( string $str )

The function takes one parameter: the string to be analyzed ($str). The crc32() function returns an unsigned 32-bit integer representing the CRC checksum of the string. (Note: On 32-bit systems, it may return a signed integer. Use sprintf('%u', crc32($str)) to ensure a consistent unsigned result across platforms.)

Here is an example of how to use the crc32() function:

PHP example of crc32()

php
<?php
$str = "Hello, World!";
$crc = sprintf('%u', crc32($str));
echo $crc;
?>

In this example, we have a string that we want to calculate the CRC checksum of. We pass the string to the crc32() function, which returns the CRC checksum as an unsigned 32-bit integer.

The output of this code will be:

console
4011902336

As you can see, the crc32() function has returned the CRC checksum of the string.

Here is another example of how to use the crc32() function to verify the integrity of a file:

How to use PHP crc32()?

php
<?php
$filename = "file_to_check.txt";
$expected_crc = 123456789;
$crc = crc32(file_get_contents($filename));
if ($crc === $expected_crc) {
    echo "The file has not been corrupted.";
} else {
    echo "The file may have been corrupted.";
}
?>

In this example, we have a file that we want to verify the integrity of. We calculate the CRC checksum of the file contents using the crc32() function and compare it to an expected CRC checksum. If the calculated CRC checksum matches the expected CRC checksum, we assume that the file has not been corrupted. Note: If $expected_crc comes from a hex string or external source, cast it to an integer (e.g., (int) hexdec($expected_crc)) before using ===.

Important notes:

  • CRC-32 is not cryptographically secure. It should only be used for basic error detection, not for security or authentication purposes.
  • It is common to convert the result to a hexadecimal string using sprintf('%08X', crc32($str)) for better readability and standard formatting.
  • For modern applications, consider using hash_file() or hash() (e.g., SHA-256) instead, as CRC-32 is rarely used for new projects.

The crc32() function is a useful tool for calculating cyclic redundancy checksums of strings and verifying the integrity of data or files. It can help make your code more versatile and flexible when working with data integrity or verifying the integrity of a file or message. By mastering this function, you can become a more proficient PHP developer.

We hope this article has been helpful in understanding the crc32() function in PHP. If you have any questions or comments, please feel free to reach out to us.

Practice

What is the function of the crc32() function in PHP?

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.