Reputation: 43
I have a database full of user user entered Barcode numbers of variious lengths.
How can I validate these barcode values to determine if the are correct format, ie, length and check digit? using php
Upvotes: 3
Views: 8337
Reputation: 362
here you go:
function isValidBarcode($barcode) {
//checks validity of: GTIN-8, GTIN-12, GTIN-13, GTIN-14, GSIN, SSCC
//see: http://www.gs1.org/how-calculate-check-digit-manually
$barcode = (string) $barcode;
//we accept only digits
if (!preg_match("/^[0-9]+$/", $barcode)) {
return false;
}
//check valid lengths:
$l = strlen($barcode);
if(!in_array($l, [8,12,13,14,17,18]))
return false;
//get check digit
$check = substr($barcode, -1);
$barcode = substr($barcode, 0, -1);
$sum_even = $sum_odd = 0;
$even = true;
while(strlen($barcode)>0) {
$digit = substr($barcode, -1);
if($even)
$sum_even += 3 * $digit;
else
$sum_odd += $digit;
$even = !$even;
$barcode = substr($barcode, 0, -1);
}
$sum = $sum_even + $sum_odd;
$sum_rounded_up = ceil($sum/10) * 10;
return ($check == ($sum_rounded_up - $sum));
}
Upvotes: 17
Reputation: 1455
I've used PHPBarcodeChecker in a project, take a look here: http://www.phpclasses.org/package/8560-PHP-Detect-type-and-check-EAN-and-UPC-barcodes.html
Hope it helps!
Upvotes: 1