Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 740
Pinakin Patel Avatar asked Sep 05 '26 01:09

Pinakin Patel


1 Answers

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));
    }
like image 140
Moshe Dolev Avatar answered Sep 07 '26 14:09

Moshe Dolev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!