search for in the  
<count_charscrypt>
Last updated: Thu, 19 May 2005

crc32

(PHP 4 >= 4.0.1, PHP 5)

crc32 -- Calculates the crc32 polynomial of a string

Description

int crc32 ( string str )

Generates the cyclic redundancy checksum polynomial of 32-bit lengths of the str. This is usually used to validate the integrity of data being transmitted.

Because PHP's integer type is signed, and many crc32 checksums will result in negative integers, you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned crc32 checksum.

This second example shows how to print a converted checksum with the printf() function:

Example 1. Displaying a crc32 checksum

<?php
$checksum
= crc32("The quick brown fox jumped over the lazy dog.");
printf("%u\n", $checksum);
?>

See also md5() and sha1().



User Contributed Notes
crc32
Johan
13-May-2005 05:12
Here is a php version of the Java String hashCode:
( produced for: http://openmusic.op.funpic.org/catalog/ )

/**
 * Calculate hash code for a string computed as
 * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
 * Equal to java.lang.String.hashCode()
 *
 * Returns an integer.
 */
function toID($link) {
   $link = (string)$link;
   $len = strLen($link);
   $sum = 0;
   for ($i = 0; $i < $len; $i++) {
       $sum = (int)(31 * $sum + getASCIICode($link[$i]));
       // echo($sum . "<br>");
   }

   return ((int)$sum);
}

// get char as int, - see example codes at intval on the subject.
function getASCIICode($caracter) {
// ...
}
gribber (_at) hellburner (dot_) net
18-May-2004 04:41
A little correction to the sfv checksum code above, this was confuseing me for a while, heading zeros was striped away.

<?php
function sfv_checksum ($filename) {
   return
str_pad (strtoupper (dechex (crc32 (file_get_contents ($filename)))), 8, '0', STR_PAD_LEFT);
}
?>
waldomonster at netjukebox dot demon dot nl
23-Apr-2004 10:48
<?php
$data
= 'dot';
echo
dechex(crc32($data));
?>

Returns 59278a3
Witch is missing a leading zero.

<?php
$data
= 'dot';
echo
str_pad(dechex(crc32($data)), 8, '0', STR_PAD_LEFT);
?>

Returns the correct string: 059278a3
arachnid at notdot dot net
13-Apr-2004 10:44
Note that the CRC32 algorithm should NOT be used for cryptographic purposes, or in situations where a hostile/untrusted user is involved, as it is far too easy to generate a hash collision for CRC32 (two different binary strings that have the same CRC32 hash). Instead consider SHA-1 or MD5.
same
01-Feb-2004 07:27
bit by bit crc32 computation

<?php

function bitbybit_crc32($str,$first_call=false){

  
//reflection in 32 bits of crc32 polynomial 0x04C11DB7
  
$poly_reflected=0xEDB88320;

  
//=0xFFFFFFFF; //keep track of register value after each call
  
static $reg=0xFFFFFFFF;

  
//initialize register on first call
  
if($first_call) $reg=0xFFFFFFFF;
  
  
$n=strlen($str);
  
$zeros=$n<4 ? $n : 4;

  
//xor first $zeros=min(4,strlen($str)) bytes into the register
  
for($i=0;$i<$zeros;$i++)
      
$reg^=ord($str{$i})<<$i*8;

  
//now for the rest of the string
  
for($i=4;$i<$n;$i++){
      
$next_char=ord($str{$i});
       for(
$j=0;$j<8;$j++)
          
$reg=(($reg>>1&0x7FFFFFFF)|($next_char>>$j&1)<<0x1F)
               ^(
$reg&1)*$poly_reflected;
   }

  
//put in enough zeros at the end
  
for($i=0;$i<$zeros*8;$i++)
      
$reg=($reg>>1&0x7FFFFFFF)^($reg&1)*$poly_reflected;

  
//xor the register with 0xFFFFFFFF
  
return ~$reg;
}

$str="123456789"; //whatever
$blocksize=4; //whatever

for($i=0;$i<strlen($str);$i+=$blocksize) $crc=bitbybit_crc32(substr($str,$i,$blocksize),!$i);

?>
sandeep_k_ghosh at hotmail dot com
15-Oct-2003 12:08
This function returns the unsigned crc32 value. I realized it's not very obvious from the current documentation.

<?php
/**
 * Function to compute the unsigned crc32 value.
 * PHP crc32 function returns int which is signed, so in order to get the correct crc32 value
 * we need to convert it to unsigned value.
 *
 * @param $str - String to compute the unsigned crc32 value.
 * @return $var - Unsinged inter value.
 */
function computeUnsignedCRC32($str){
  
sscanf(crc32($str), "%u", $var);
   return
$var;
}
?>
xethmir at yournextclient dot com
16-Jul-2003 09:12
This is a really simple way of displaying the crc-32 hexadecimal code/checksum for a file... (absolute paths are more reliable)

<?
$file
= "http://foo.net/bar.jpg";

// Read the file into an array
$data = file($file);

// Join the array into a string
$data = implode('', $data);

// Calculate the crc
$crc = crc32($data);

//convert from decimal to hexadecimal
$crchex=DecHex($crc*1);

//echo the result
echo "$crchex";
?>
sergi34 at megacceso dot com
10-Jun-2003 05:27
If you want to display a crc checksum correctly, you need to format it to unsigned because PHP int type is signed.

example:

<?php
$crc
= crc32("String where we calculate the checksum");
printf("%u", $crc);
?>
quix at free dot fr
05-May-2003 03:19
I needed the crc32 of a file that was pretty large, so I didn't want to read it into memory.
So I made this:

<?php
   $GLOBALS
['__crc32_table']=array();        // Lookup table array
  
__crc32_init_table();

   function
__crc32_init_table() {            // Builds lookup table array
       // This is the official polynomial used by
       // CRC-32 in PKZip, WinZip and Ethernet.
      
$polynomial = 0x04c11db7;

      
// 256 values representing ASCII character codes.
      
for($i=0;$i <= 0xFF;++$i) {
          
$GLOBALS['__crc32_table'][$i]=(__crc32_reflect($i,8) << 24);
           for(
$j=0;$j < 8;++$j) {
              
$GLOBALS['__crc32_table'][$i]=(($GLOBALS['__crc32_table'][$i] << 1) ^
                   ((
$GLOBALS['__crc32_table'][$i] & (1 << 31))?$polynomial:0));
           }
          
$GLOBALS['__crc32_table'][$i] = __crc32_reflect($GLOBALS['__crc32_table'][$i], 32);
       }
   }

   function
__crc32_reflect($ref, $ch) {        // Reflects CRC bits in the lookup table
      
$value=0;
      
      
// Swap bit 0 for bit 7, bit 1 for bit 6, etc.
      
for($i=1;$i<($ch+1);++$i) {
           if(
$ref & 1) $value |= (1 << ($ch-$i));
          
$ref = (($ref >> 1) & 0x7fffffff);
       }
       return
$value;
   }

   function
__crc32_string($text) {        // Creates a CRC from a text string
       // Once the lookup table has been filled in by the two functions above,
       // this function creates all CRCs using only the lookup table.

       // You need unsigned variables because negative values
       // introduce high bits where zero bits are required.
       // PHP doesn't have unsigned integers:
       // I've solved this problem by doing a '&' after a '>>'.

       // Start out with all bits set high.
      
$crc=0xffffffff;
      
$len=strlen($text);

      
// Perform the algorithm on each character in the string,
       // using the lookup table values.
      
for($i=0;$i < $len;++$i) {
          
$crc=(($crc >> 8) & 0x00ffffff) ^ $GLOBALS['__crc32_table'][($crc & 0xFF) ^ ord($text{$i})];
       }
      
      
// Exclusive OR the result with the beginning value.
      
return $crc ^ 0xffffffff;
   }
  
   function
__crc32_file($name) {            // Creates a CRC from a file
       // Info: look at __crc32_string

       // Start out with all bits set high.
      
$crc=0xffffffff;

       if((
$fp=fopen($name,'rb'))===false) return false;

      
// Perform the algorithm on each character in file
      
for(;;) {
          
$i=@fread($fp,1);
           if(
strlen($i)==0) break;
          
$crc=(($crc >> 8) & 0x00ffffff) ^ $GLOBALS['__crc32_table'][($crc & 0xFF) ^ ord($i)];
       }
      
       @
fclose($fp);
      
      
// Exclusive OR the result with the beginning value.
      
return $crc ^ 0xffffffff;
   }
?>
lander at liebe dot nu
20-Apr-2003 09:22
A simple and quite fast (10ms/Mb) way to generate checksums used with the popular SFV (Simple File Verification) format. strtoupper() isn't really needed, but the output looks better this way ;)

<?php
function generate_sfv_checksum($filename) {
 $sfv_checksum = strtoupper(dechex(crc32(file_get_contents($filename))));
 return $sfv_checksum;
}
?>
spectrumizer at cycos dot net
29-Dec-2002 05:30
Here is a tested and working CRC16-Algorithm:

<?php
function crc16($string) {
 
$crc = 0xFFFF;
  for (
$x = 0; $x < strlen ($string); $x++) {
  
$crc = $crc ^ ord($string[$x]);
   for (
$y = 0; $y < 8; $y++) {
     if ((
$crc & 0x0001) == 0x0001) {
      
$crc = (($crc >> 1) ^ 0xA001);
     } else {
$crc = $crc >> 1; }
   }
  }
  return
$crc;
}
?>

Regards,
Mario

<count_charscrypt>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT