Tutorial: Using Barcode ActiveX to Generate Barcodes in PHP Web Applications

This article explains how to create barcode images in PHP. The solution in this article requires PHP 5.0, Morovia Barcode ActiveX 3.3 (and above), and a web server (either IIS or Apache).

In HTML, you can't embed image files directly. You use HTML tag img with its attribute src set to the path of the image file, such as:

<img src="barcode.png" />

In normal case, the file referenced barcode.png must exist in the server. Because we want to create barcode dynamically, we need to come up another php script to create the barcode image dynamically and send out to the browser, like this:

<img src="getimage.php?id=1233456" />

The Barcode ActiveX software includes a classic ASP example that demonstrate creating image on the memory dynamically and sending to the browser. Unfortunately we have not found a similar solution in PHP. Right now, you have to store the image files on disk and load it at the later time. Utilizing disk files does have a performance advantage, as you can optimize calls to Barcode ActiveX (which is expensive). For example, you do not need to call Barcode ActiveX again on the same data. This article will show you how to use hash codes to achieve the optimization.

Checking PHP Configuration

Before you start, first make sure that the PHP is enabled on your application, and the version is 5.0 or above.

Creating a Directory to Store Image Files

Now create a directory to store image files. In this example, we use c:/Inetpub/WebAppData. This directory must be writable to the user that web server runs - in IIS it is usually IUSR_MACHINENAME.

Image Caching/Retrieving Strategy

Next we need to decide how to efficiently retrieve an image if it is already created. Morovia Barcode ActiveX provides several dozen options. In most cases you probably only need to change one or two per request. Let's assume that in your application all barcodes have the same properties except message (the data to be encoded). You can then use the value of message as the image file. A better solution is to create a hash value, and use this value as the file name, as you do not need to worry about escaping characters not allowed by the file system, and retrieval is likely faster.

$md5_string = md5($dataToEncode);
$filepath = "c:/inetpub/WebAppData" . "/" . $md5_string . ".png";
if (file_exists($filepath)) {
    /* do nothing */
} else {
    try {
        $encoder = new COM("Morovia.BarcodeActiveX");
        $encoder->Symbology = 5; /* Code 128 */
        $encoder->Message = $dataToEncode;
        ... /* set other default properties */
        $encoder->NarrowBarWidth = 20; /* X dimension */
        $encoder->BarHeight = 500;   /* 0.5 inch height */
        $encoder->ShowComment = false; /* disable comment */
        $encoder->TexAlignment  = 3; /* align human readable justify */
        $encoder->RasterImageResolution = 96;
        $encoder->ExportImage($filepath, 5); /* 5 - PNG image format */
    } 
    catch (Exception $e) {
        $com_success = false;
        $error_msg = $e->getMessage();
    }
}

In the code above, we invoke Barcode ActiveX when we are unable to find an existing file that matches the request by searching the image directory based on the md5 hash value on the data to be encoded.

If you are using Barcode Lite, change the ProgID to Morovia.BarcodeLite.

Note that you must set Symbology first before changing Message property, as different barcode formats have different rules on its encoding character sets and default values.

Displaying Barcode Images

You can place the code in the front end script, or at the back end script. We choose front end script because if there is an error in barcode image creating process, we can handle it by not emitting the img tag, as the code below:

if ($com_success) {
  printf("<img src=\"getimage.php?file=%s.png\"/>\n", $md5_string);
} else {
  printf("<p style='color:red'>Error in getting image(%s).</p>\n", 
            $error_msg);
}

If the barcode image requested was successfully created, the code emits IMG tag, which links to the back end script (we will talk about this soon). Otherwise it prints an error message.

Backend Script

In the backend, the getimage.php script searches the image directory, and if found, it reads the image data and sends to the browser.

/* getimage.php requires a parameter entered through GET. */

$file_string = $_GET['id'];
if (strlen($file_string) <= 0 ) {
    header ("HTTP/1.0 404 Not Found");
    return;
}

$image_dir = "c:/inetpub/WebAppData";

$filepath = $image_dir . "/" . $file_string;

if (file_exists($filepath)) {
    $fm = @fopen($filepath, "rb");
    if (!$fm) {
        header ("HTTP/1.0 505 Internal server error");
        return;
    }

    header("Content-Type: image/png");
    
    $begin = 0;
    $end   = filesize($filepath);
    
    fseek($fm, $begin, 0);
    $cur = $begin;
    
    while(!feof($fm) && $cur < $end && (connection_status()==0) ) {
        print fread($fm, min(1024*16, $end-$cur));
        $cur += 1024*16;
    }
} else {
    header ("HTTP/1.0 404 Not Found");
    return;
}