Web Programming, Linux System Administation, and Entrepreneurship in Athens Georgia

Quick PHP Script to Generate a Barcode

This is a really quick script I came up with to generate a Code-39 Barcode. Many thanks to
Matthew Welch who created the Free 3 of 9 Barcode Font. PHP’s imagettftext function makes this pretty simple.

The $barcode_font referenced below is available from the link above ‘3 of 9’ font. The $plain_font is just a font file that I copied from /usr/share/fonts/default/Type1/ on a Linux box.

This script create a nice looking barcode with the text underneath it like this:

< ?php

$number = isset($_GET['number']) ? $_GET['number'] : '';

$barcode_font = dirname(__FILE__).'/fonts/FREE3OF9.TTF';
$plain_font   = dirname(__FILE__).'/fonts/plain.pfb';

$width = 200;
$height = 80;

$img = imagecreate($width, $height);

// First call to imagecolorallocate is the background color
$white = imagecolorallocate($img, 255, 255, 255);
$black = imagecolorallocate($img, 0, 0, 0);

// Reference for the imagettftext() function
// imagettftext($img, $fontsize, $angle, $xpos, $ypos, $color, $fontfile, $text);
imagettftext($img, 36, 0, 10, 50, $black, $barcode_font, $number);

imagettftext($img, 14, 0, 40, 70, $black, $plain_font, $number);

header('Content-type: image/png');

imagepng($img);
imagedestroy($img);

?>

5 Comments

  1. bered

    thanks a lot for sharing how can i add one more line for showing information as a text below to barcode text from database fileld

  2. vijay

    I m trying to using this script but i m unable to get the barcode as it prints the string whatever we pass to it.

    Any help….

  3. Dean

    Hey vijay,
    You can’t get the barcode? perhaps you should try this type of barcode
    https://www.keepautomation.com/products/net_barcode_WinForms/barcodes/data_matrix.html
    For your reference.
    Hope you can get what you wanted.

  4. Benno

    I managed to print what looked like barcodes using this method, but the barcode scanner couldn’t recognise them :/

  5. Edward

    Hello!

    I find your nice and easy code.

    I test it with my OpenSUSE 12.3 server, but there is no right $plain_font (plain.pfb).

    OpenSUSE 12.3 font path is: /usr/share/fonts/Type1/

    Any idea ?

Leave a Reply

Your email address will not be published. Required fields are marked *

© 2025 Brandon Checketts

Theme by Anders NorenUp ↑