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:

Example 1:


Text: “0” (Default)

Size: “20” (Default)

Code Type: “Code128” (Default)

Orientation: “Horizontal” (Default)

HTML Source Code:

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



Example 2:


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" />



Example 3:



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" />



Example 4:


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" />



Example 5:


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" />



Example 6:


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" />


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:

158 replies on “How To Create Barcodes in PHP”

Hello, great examples. How would you make it so that the barcode is generated from a form. Or rather, have a user input the numbers and then the barcode generated from that?


Here is a simple example of how to accomplish what you are looking for

<form action=”” method=”get” name=”barcode-form”>
<input type=”text” id=”text” name=”text” value=”testing” />
<input type=”submit” name=”barcode-button” />

Hello sir, I really want to include it in my code so that it can be display on my webpage but its generating something else that I couldn’t interpret

I use this code in php but after produce barcode 128 default my barcode scanner not scan data

Well done. I have been working with Oracle since the early days (circa 1988) and not seen any facility to produce barcodes with in Oracle. Now I am working with Oracle R12 E-Business an still see no improvement. I am hoping to get the barcoding integrated into producing barcoded letters. I am looking into adding UK Royal Mail postcode into each letter sent out to clients. Sadly Oracle have not made my job easy. Your work has given me some great Ideas. Thank you

Nice implementation without the need for any font files.

To add text, use the GD library to inject text before the “// Draw barcode to the screen” comment. Or use the barcode image in a new GD image.

To save the image to a folder, delete the row after the “// Draw barcode to the screen” comment. Then modify the imagepng() function on the next row, add a filename as second parameter.

Great code, I will use this with FileMaker, inserting the resulting image into a container field using my web server for the PHP. The best part of this is there is no need to any plugins or fonts. I have years experience implementing barcodes and this is the simplest ever! THANKS

Please update the USAGE syntax in the associated PHP file as the current syntax is incorrect. It is given as whereas it should have been You see the question mark (?) ? That’s what is important. You have correctly listed in your examples but it is incorrect in the source code of the file and someone who uses the code from the source file will NOT be able to run the code as is and get the output correctly. So please update the ampersand to question mark on line 9 in source code.


Compliments, and thank you for this great barcode code, really simle and very effective.

I have a queystion. How can i add the numbers and letters under the barcode. So the image will be complete, barcode image and barcode number.

Thanks this is very helpfull

I need to add some other details along with the barcode. Such as barcode number, product weight and price. How can i do that.? How to edit this file to get an output as required?

Thanks for code. It’s really very helpful for me. When i crate barcode with img src there is no name during barcode scanning. I want to print barcode with img src. Please help.

I normally don’t comment on sites but felt that you’ve given us a great piece of code here – and free of charge too. Many thanks. Works like a charm. To make sure it was working, I tested it with ‘QR Droid’ and it read it perfectly (obviously)

This code works beautifully. Is there an easy way (i’m using code128) to increase the bar width? Two of my three scanners are having an issue and I think it’s the bar width that’s giving them a problem.

Great work David,

Please, just a question. It is possible with this method show a EAN13 code?

Thank you very much!!

I’m having problems with code39 type, I always get a fragment of the barcode, not the whole image. Any hint? I’m using the function to generate the barcode on-the-fly and embed it into a PDF with FPDF php class.

It seems that code39 barcode is wrong, I’ve used another program to generate the barcode and is quite different from the barcode generated by your script. Is there something to solve this problem?

Hi David

Is there any way for fixing the barcode width like if barcode generate from 6 digits then the width is: 2.625 inches. and if the digits are 13 then also barcode width is:- 2.625 inches.

If it is possible please tell me.


please help me.coming error in my system

The image “” cannot be displayed because it contains errors.

how to apply Tilde in code 128??? like when i give 123~009ABC as the input the output is the same….but I want the output to be 123 ABC

Thank you so much for this – a clean, simple, easy to understand bit of code. Far simpler than all the other barcode generators I’ve looked at so far.

First of all, thanks for the great peace of code.

However, I’ve encountered some problems with commercial barcode reader. I believe it might have something to do with the checksum. This I do not know, could someone maybe confirm this – or even better, tell me a way around this?

However, I do have noticed that mobile phone apps like Quickmark do read the generated codes (code128 and code39 at least) Ok. Unfortunately for me this does not help much, since I needed to use computer with USB-plugged reader for my purpose.

I’m currently looking to use this in an application. As I was testing I noticed a real case would contain an & (ampersand) in the text string passed. Currently, this is causing only the characters before the & (ampersand) to be used in the barcode generated. Is there a work around for such a case? I need to allow & (ampersand) in the string.

I found a work around for my & (ampersand) issue. Before I add my text string to the src value of the img tag I run it through php’s urlencode and htmlentities like this:
Then I’ve added the decoding equivalent function to your barcode file like this:
$text = (isset($_GET[“text”])?urldecode(html_entity_decode($_GET[“text”])):”0″);
Note* I’ve reversed the order of process because htmlentities was done last, so the html_entity_decode should be preformed first, then urldecode.
Hope this helps others!

how can i use this code for a pop up window that contains both the php barcode script and some html coding? I tried adding codings above the <?php and this just turns the entire page white instead of generating the barcode…Any ideas for this fix?

i am trying to insert php html coding above by using these lines…the issue i am having is the page does not generate the barcode image..Should i insert the code below?

echo "this is how generating is done”;

corrected code below…
*php starts here
echo “this is how generating is done” ends here*

*php starts here
// Get pararameters that are passed in through $_GET or set to the default value
$text = (isset($_GET[“text”])?$_GET[“text”]:”0″);
* ends here

i cannot seem to use my Adesso Barcode Scanner with after barcodes are generated…can someone help?

There appears to be a typo in the “Code39” php code. The trailing asterisk of a Code39 bar code appears need an extra “1” added to generate valid codes. So the correct line would read:

$code_string = “1211212111” . $code_string . “1211212111”;

Actually I believe the first asterisk is incorrect. A code39 asterisk is coded as: bWbwBwBwb
I think the statement should be: $code_string = “121121211″ . $code_string . “121121211″;

I want to save the generated barcode and to take the print out using barcode printer. Can any body have some idea and please tell the related code to make it easier.

on the near the very end where it says imagepng($image), the second parameter is the name of a file to take the image so try imagepng($image,”testfile.png”);
It’s all in the php manual

How do you change 128 encoding sets in the middle of a string? We have to start in Set B, change to Set C part way through the full string to maximise the compression where there is an even set of numeric characters and then back to Set B again. We tried adding “Start C” to the string but this was also just turned into bars. Thanks, any pointers would be much appreciated.

I have tried this code, and the output is a blank page. What should I do?
GD libary is installed on web server. I use .
Thanks in advice.

I have a problem with code 39. I don’t know why, but code 39 have to end with two strong and one slim line, but in your code ending with three strong lines. My barcode reader canť read the barcode, so I repair the mistake in code with: $code_string = “1211212111” . $code_string . “1211212111”; In code in github is missing the last slim line.

Thank you

To add width / thickness functionality:

// Get thickness parameter from $_GET:
$thickness = ( isset( $_GET[“thickness”] ) ? $_GET[ ‘thickness’ ] : 1 );

change the following three lines in the existing code:
$img_width = $code_length;
$img_width = $code_length * $thickness;

$location = 10;
$location = 10 * $thickness;

$cur_size = $location+(substr($code_string, ($position – 1), 1) );
$cur_size = ($location+(substr($code_string, ($position – 1), 1) )*$thickness);


<- here's an example. It doesn't work if the code is not full length.

Testing this is difficult because it requires a scanner. I’ve been trying to test using a couple apps and they don’t seem to be reading the barcode. Do you recommend any apps that are capable of testing the encoded value?

Thanks ahead of time.

The QuickMark app is working well for me. The iOS version has a companion Mac app that lets you scan barcodes on your iPhone/iPad and automatically paste it to your Mac. It’s very useful for testing this great barcoding solution.

Hi ,
Good tutorial. I have generated the barcode in code-128 format. Now to print it using zebra GT820 printter.

Hi. could you help me how can I receive bar-code data from bar-code scanner and send to msql automatically

Dear mr. tufts,
depends the width of the image on the text-length?
I’m asking because i’m not sure if the code is readable if i resize the generated image to make the barcode bigger and – as a consequence – easier to scan.

Best regards

For some reason the image is not displaying for me. I have barcode.php and index.php in the same directory. I have checked and found that gd library is installed. I am using WAMP latest version. 64 bit.

Following is the code if index.php:

Do i need to include the file barcode;php before using it?

Great Job, thak you David, I do not know really much about barcode how to change the code using Data Matrix

I always get the last bar 1 pixel to wide, and it breaks Code39.

I changed $cur_size in imagefilledrectangle to $cur_size -1 and now it works.

if ( strtolower($orientation) == “horizontal” )
imagefilledrectangle( $image, $location, 0, $cur_size-1, $img_height, ($position % 2 == 0 ? $white : $black) );
imagefilledrectangle( $image, 0, $location, $img_width, $cur_size-1, ($position % 2 == 0 ? $white : $black) );

I fiddled around with this code for a couple hours. Its returning ‘The image … cannot be displayed becouse it contains errors.’ GD installed on a XAMPP ubuntu install. Everything looks ok. Moving onto something else for now.

I’m getting the same error, whatever codetype I use: The image XXXXXXXXX cannot be displayed, because it contains errors. GD installed.

I used the code in my laptop locally and it works great.
Now I uploaded the code on the server but the barcode is not seen, that was missing on the server?

cheap toms shoes,cheap toms,cheap toms shoe,discount toms shoes,discount toms,toms shoes,buy toms,toms shoes for sale,cheap toms shoes for sale,toms shoes outlet,toms shoes for sale,toms shoes,toms shoes outlet,toms shoes for sale,toms shoes cheap,to…

They were collected primarily through police reports in 2007, death certificates and the number of fatalities registered by the Not in Traffic Surveillance system, a virtual data collector of details regarding nontraffic crashes nationwide.. Below we i…

Which Code 128 set does this support?

I need to produce some labels for a third party that specifically require Code 128A. I don’t see a way to specify A, B or C in this code, but if I can be sure that it’s producing A, then it should work great anyway 🙂 (If not, then I suppose I’ll need to keep looking.)

One way or the other, thanks for what looks to be a very useful library!

Never mind, I looked a bit further into the code and found out that it’s Code 128B. Fortunately I also found that adding in support for Code 128A wasn’t terribly difficult 🙂

Thanks for the great code David! I have started using it to help my dad who is a practicing doctor in a 3rd world country to keep track of his patients and inventory management!

Thank you so much David!

I have been allergic to PHP since 2001 since battling with a 20 line lookup code for 23 hrs and 49 minutes minutes before a client website delivery deadline! And after reading your beautiful code I realise that I am still a hopeless case! Thank you once again.

Hi David,

I am getting a lot of error with your code in my wamp server. They are all the same though and read.

“Notice: A non well formed numeric value encountered in C:\WAMP\www\barcode.php on line 103”

Please help.

There is also a “Warning: Cannot modify header information – headers already sent by ” error but I dont think that is preventing the image from showing up. Currently there is just a broken image link that shows up in my page.

So the errors disappears when I remove the “&Size=60” part from the string. Still cannot see the image though. not sure what I am doing wrong. Was working fine on an older server yesterday.

add this:

function imagecenteredstring ( &$img, $font, $xMin, $xMax, $y, $str, $col ) {
$textWidth = imagefontwidth( $font ) * strlen( $str );
$xLoc = ( $xMax – $xMin – $textWidth ) / 2 + $xMin + $font;
imagestring( $img, $font, $xLoc, $y, $str, $col );

then replace the end with this:
$text_height = 20;
$border = 10;
$img_width = $code_length;
$img_height = 2*$border + $size + $text_height;

$image = imagecreate($img_width, $img_height);
$black = imagecolorallocate ($image, 0, 0, 0);
$white = imagecolorallocate ($image, 255, 255, 255);

imagefill( $image, 0, 0, $white );

$location = 10;
for ( $position = 1 ; $position <= strlen($code_string); $position++ ) {
$cur_size = $location + ( substr($code_string, ($position-1), 1) );
imagefilledrectangle( $image, $location, $border, $cur_size, $border + $size, ($position % 2 == 0 ? $white : $black) );
imagecenteredstring($image, 6, 0, $img_width, $border + $size, $text, $black);
$location = $cur_size;

// Draw barcode to the screen
header ('Content-type: image/png');
$image=imagerotate($image, 90, $white);

to get a white border, the text under the image and simplify rotation

Hello auvo1001

I use your forked library. But I can not get the text. Can you please help?

Hi David , thanks for your post .
But I have a problem , I try create a barcode on Microsoft Excel , but the result different with barcode on the website . the result on website (with your articel) is very” length .
my question is , How the minimize size the barcode ??
thanks , I will wait your reply 🙂

Hi David,
This works like a charm. I just tweaked it a bit and put the main functionality in a class function for it to be used as a CodeIgniter library. its working beautifully.

Dear David,
Please, I am a grad student and my goal is to use this to develop measuring tools like barcode rulers protractors etc. Please can you give a hint on how to do this for ruler calibrations in millimeters, centimeters on inches? And please, I am a beginner in java and have moderate level of knowledge in R programming skills.


This is really cool stuff. It is easy to use in any frame work and saved me a lot of development time.
Good job

Hi David – I know I am coming to this party yet but I just want to congratulate you on a really good job. Not only is the code useful, it is also so well presented here and on the GITHUB page. As a new user of PHP I am deeply grateful for your help in allowing me to become productive.

this is the easiest code I could find, thanks a lot!
I made a modification and will share for anyone who doesn’t know how to do it themselves, it took me a while to figure this out. You can print the barcode to screen and save the barcode with the barcode number as the file name at the same time.

// Draw barcode to the screen or save in a file
if ( $filepath==”” ) {
header (‘Content-type: image/png’);
} else {

( ! ) Warning: imagepng() [function.imagepng]: Unable to open ‘codesss’ for writing: Permission denied in D:\WAMP_projects\barCodeGenrator\barcode.php on line 155

i am facing this error when i want to save png file in the folder “codesss”. Kindly help me sir!

You have a small bug in your code: if print = true then orientation needs to be horizontal. Your script cannot handle bar codes that are vertical and also printing the text.

For those who are having trouble scanning the barcodes, try changing the line
imagefilledrectangle( $image, $location*$SizeFactor, 0, $cur_size*$SizeFactor, $img_height, ($position % 2 == 0 ? $white : $black) );
imagefilledrectangle( $image, $location*$SizeFactor, 0, $cur_size*$SizeFactor-1, $img_height, ($position % 2 == 0 ? $white : $black) );
Thanks for the great code

Hi David

Is there any way for fixing the barcode width like if barcode generate from 6 digits then the width is: 250px and if the digits are 13 then also barcode width is:- 250px.

If it is possible please tell me how ? it’s very urgent for me .
if any one else have idea then pls explain me


Thank you. Elegance in simplicity. I found some libraries that required all sorts of major server installations to achieve what you did in a 153 lines of code written in 2003.

composer require elminson/barcode

Basic use:
namespace Elminson\BarCode;

require_once(__DIR__ . ‘/vendor/autoload.php’);

$barcode = new BarCode(‘code128’);
$barcode->SaveBarcodeToDisk(); //Save to folder

Hello there

I create a Package library for this

composer require elminson/barcode

Basic use:
namespace Elminson\BarCode;

require_once(__DIR__ . ‘/vendor/autoload.php’);

$barcode = new BarCode(‘code128’);

My scanner doesn’t read generated code:(( At the same time it read perfectly on other site. I noticed, that difference in the line’s width. Here is 2 codes The upper generated by script, other generated on the site, the same number. First code scanner can not read, second is ok.

Why should it be?

Hi David – This is a great product – Kudos …
I was wondering if you have any add-on to the bardcode library to enable the generation of PDF417

Hi David. Is there any way to generate multiple barcode using your script. I tried to generate using for loop,but as i redirect to another page the image is not saved to filepath. is there any solution?

Hi, I am using cakePHP and it is not working for me. I copied barcode.php file under vendors folder and added following code to products.ctp file.

echo “”;

I only can see broken image. Please advise me.

Thank you,

Comments are closed.