Categories
PHP

How To Create Barcodes in PHP

A few years ago I needed a way to generate barcodes on-the-fly using PHP, at the time there were several solutions available at a steep cost, so I wrote this script that generates barcodes in four barcode formats including Code 128, Code 39, Code 2of5, and Codabar. With a little over 100 lines of code you have the options of “vertical” or “horizontal” display, varying barcode heights, and one of four barcode formats. It does require the GD Library to be installed as a module in PHP.

This code is available for use under the MIT License

View the code here: https://github.com/davidscotttufts/php-barcode/


Example 1:

Parameters:

Text: “0” (Default)

Size: “20” (Default)

Code Type: “Code128” (Default)

Orientation: “Horizontal” (Default)

HTML Source Code:

<img alt="testing" src="/code/barcode.php" />

Result:

0


Example 2:

Parameters:

Text: “testing”

Size: “20” (Default)

Code Type: “Code128” (Default)

Orientation: “Horizontal” (Default)

Print: “true”

HTML Source Code:

<img alt="testing" src="/code/barcode.php?text=testing&print=true" />

Result:

testing


Example 3:

Parameters:

Text: “TESTING”

Size: “40”

Code Type: “Code39”

Orientation: “Horizontal” (Default)

Print: “true”

HTML Source Code:

<img alt="TESTING" src="/code/barcode.php?codetype=Code39&size=40&text=TESTING&print=true" />

Result:

TESTING


Example 4:

Parameters:

Text: “12345”

Size: “40”

Code Type: “Code25”

Orientation: “Horizontal” (Default)

HTML Source Code:

<img alt="12345" src="/code/barcode.php?codetype=Code25&size=40&text=12345" />

Result:

12345


Example 5:

Parameters:

Text: “123ABC”

Size: “40”

Code Type: “Codabar”

Orientation: “Horizontal” (Default)

HTML Source Code:

<img alt="123ABC" src="/code/barcode.php?codetype=Codabar&size=40&text=123ABC" />

Result:

123ABC


Example 6:

Parameters:

Text: “The Real David Tufts”

Size: “40”

Code Type: “Code128” (Default)

Orientation: “Vertical”

HTML Source Code:

<img alt="The Real David Tufts" src="/code/barcode.php?text=The%20Real%20David%20Tufts&orientation=vertical&size=40" />

Result:

The Real David Tufts


Please leave comments with additions or improvements to this script. One possible area of improvement for Code 128 is figuring out how to add keyboard commands (i.e. SHIFT, DEL, FNC 1, etc.) to the barcode.

Again, you can view the code here: https://github.com/davidscotttufts/php-barcode/