Quick PHP Script to Generate a Barcode

Posted on July 20th, 2010 in Uncategorized by Brandon

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');



5 Responses to 'Quick PHP Script to Generate a Barcode'

Subscribe to comments with RSS or TrackBack to 'Quick PHP Script to Generate a Barcode'.

  1. bered said,

    on September 12th, 2011 at 6:13 pm

    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 said,

    on September 27th, 2011 at 12:51 pm

    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 said,

    on February 22nd, 2012 at 9:49 pm

    Hey vijay,
    You can’t get the barcode? perhaps you should try this type of barcode
    For your reference.
    Hope you can get what you wanted.

  4. Benno said,

    on May 2nd, 2012 at 10:20 pm

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

  5. Edward said,

    on December 3rd, 2013 at 6:33 am


    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 ?

Post a comment