[英]How do i validate a barcode number using php
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
使用PHP
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));
}
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 我在一个项目中使用过PHPBarcodeChecker,请在此处查看: http ://www.phpclasses.org/package/8560-PHP-Detect-type-and-check-EAN-and-UPC-barcodes.html
Hope it helps! 希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.