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:
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:
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:
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:
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:
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:
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/
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?
Carlos,
Here is a simple example of how to accomplish what you are looking for
<form action=”http://www.davidscotttufts.com/code/barcode.php” method=”get” name=”barcode-form”>
<input type=”text” id=”text” name=”text” value=”testing” />
<input type=”submit” name=”barcode-button” />
</form>
nice sir ji i want to show this code (barcode.php)
thank you ….
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
Nice, going to give this a try.
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
Is their a way to add the text “crc” under the barcode as well?
Hi,
great code
can i know the code to save image in a folder..not in a browser
Hi, great post. Is there any way to put the alt value under the barcode? Thanks.
Thanks!
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.
How to send the generated bar image to the godex barcode printer? Do anyone have any idea?
This worked like a charm!
Thanks for the great work
i apply the same concept I am not able to print this barcode in all browsers. what’s the reason?
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
hi nice code its really helpfull to me
Thank you
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.
Thanks.
fpmgonline, thanks for pointing that out, I have made the change.
Hello sir
When i print this code then Barcode scanner can’t read it. But my barcode scanner read other barcode label. Please help.
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?
Hii, This is very helpfull. But I have a question that how to print the barcode number and product price along with the barcode?
Hi Rijesh. Have you find out how to do it? I am also seeking answer for the queston.
Super cool men, this is what i was looking for 😉
[…] I stumbled upon this post by David Scott Tufts who had developed a PHP script which will generate barcodes “in four barcode formats […]
Hi,
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.
Hi sanjay, I have not created any code yet for outputting the text, I don’t think it would be very difficult for you to add that functionality.
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)
Thanks Martin, glad to hear that you can use this code!
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.
Really really good job… I’ll gve it a spin. thanks David
nice work
very helpful to me!!!
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.
Thanks,
Paramjeet
please help me.coming error in my system
The image “http://192.168.1.80:98/ABBYS/barcode/bar/testingutyuytuiyiyu” cannot be displayed because it contains errors.
Great Job!!
Hello,
Does it generate code 128 subset C ?
excellent….made my work in few seconds.
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
Thanks.
Its very flexible. Very easy to use
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.
Thanks, it’s very helpful post.
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.
@Michael
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:
htmlentities(urlencode($asset[‘asset_name’]));
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?
<?php
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
nice share. iam try this code normaly is work for me but when iam using jquery modal is not work. because barcode image not view. just only code. this my error. http://gyazo.com/f578983038b8433b191583b1e3a9214a
Thanks
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.
So does this wonderful code do 128 SET C?
Any way to manage the width of the code?
Any way to make the barcode smaller in width? I have a required max width of 105mm…
Awesome code… Looking forward to use in next project
Not working on linux mint 17
Your environment is probably not set up correctly.
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;
to:
$img_width = $code_length * $thickness;
$location = 10;
to:
$location = 10 * $thickness;
$cur_size = $location+(substr($code_string, ($position – 1), 1) );
to:
$cur_size = ($location+(substr($code_string, ($position – 1), 1) )*$thickness);
Tried this, but in code 128 it changes the output.
The problem comes when the code is longer, and includes lots of data.
479440520200360820001512800000000000000000124520140917
<- here's an example. It doesn't work if the code is not full length.
it’s working well with CODE39. Thank you!
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.
Works great! Thank you for writing the code!
Excellent, Thank you! This will save me a ton of work compared to other complex/bloated php barcode software
Hi… thanks for the tutorial.. is it possible to display the number or text just below the barcode?
Hi ,
Good tutorial. I have generated the barcode in code-128 format. Now to print it using zebra GT820 printter.
could you help me add numer in below barcode ? Thank a lot
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
Markus
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!
it’s possible generate barcode with text in bottom? like this: http://www.barcoding.com/images/Barcodes/code93.gif
thank you david for your program you help me alot and saves time.
The barcode is generated but not readable with a scanner…
I ran into the same issue. Playing around with the output I found that increasing the thickness (per the instructions in another comment here) did the job. For my scanner a thickness of 2 or larger works like a charm.
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) );
else
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.
Legendry. Cheers!
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…
thank you so much, mr. david 🙂
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.
Thank you David!
how can i read the barcode and save into mysql database,
you can add this
example : ?text=no_lot);?>
Thank you David!
how can i read the barcode?
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.
Hi all,
I need to add another image under the barcode. Appreciate your help please.
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');
if($orientation!='horizontal')
$image=imagerotate($image, 90, $white);
imagepng($image);
imagedestroy($image);
}
to get a white border, the text under the image and simplify rotation
Hi Dave and Madalin,
Great posts. Thanks for your help. I forked Dave’s github, added Madalin’s code, and repackaged it into another downloadable github. Thanks for putting this together. I wanted to share so everyone would benefit.
https://github.com/theresilientdeveloper/php-barcode
Hello auvo1001
I use your forked library. But I can not get the text. Can you please help?
i want to type number under the bar code?
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 🙂
sorry david , How the minimize length the barcode ? not the size ..
How can I use this to generate PDF in php?
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.
scott D.T Thanks You made my day. thank you all
Hi! I just want to add text at the bottom of the barcode (code 128). How can I do it?
Brilliant, mate! Thank you
Hello Sir how i can set height,width,postion and save it to database.
Hello Sir how i can save barcode generated png image in database and folder
imagepng($image, $documnetRootPath.”barcode.png”);
BarCode always returns same… 🙁
Bar code reader doesn’t fetch value from paper,
CHEERS!
Thank you!!! How to auto generate the Barcode 128 URL of a current webpage?
And if it’s possible how to auto generate random barcode number ??
How to autogenerate barcode number (Only 1 time generation per URL) and save it to database?
is there any way to integrate this to the wordpress?
Great tool, however, is there a way to lower the text size when it is displayed?
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.
Thanks.
Work perfect, thanks.
This is really cool stuff. It is easy to use in any frame work and saved me a lot of development time.
Good job
Is there any way to add padding to the white space between the black lines of the barcode? Some older scanners need the space to read easier.
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.
Thanks a Lot Buddy 🙂
That was beautiful, thanks for code.
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’);
imagepng($image);
imagepng($image,”$text.”.png);
imagedestroy($image);
} else {
imagepng($image,$filepath);
imagedestroy($image);
}
how to add the text again at top of image? Top: Testing1 Bottom: Testing 2. Thanks a Lot..
Works like a charm! Thank you very much! 😉
I have a problem using it with html2pdf. Can u give me a supoort please?
( ! ) 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.
Very very thanks this simple & great for my PHP
Vertical barcode not showing the text after the image.
Can you please fix the issue?
I have created a fork here: https://github.com/davidscotttufts/php-barcode/compare/master…kurdtpage:patch-2
Easy to use and works great! thanks!
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) );
to
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
Thanks,
Mitesh
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.
Really awesome stuff what i was looking for . Thanks
help me how to save barcode to folder
Installation
composer require elminson/barcode
Basic use:
namespace Elminson\BarCode;
require_once(__DIR__ . ‘/vendor/autoload.php’);
$barcode = new BarCode(‘code128’);
$barcode->setText(“Testing”);
$barcode->setPrint(true);
$barcode->setTextColor(“#ff9900”);
$barcode->setBgColor(“#cccccc”);
$barcode->setFileName(“test”);
$barcode->setFilepath(__DIR__.”/temp/”);
$barcode->generate();
$barcode->SaveBarcodeToDisk(); //Save to folder
$bardode->DestroyBarcode();
how can we create a download link?
Hello there
I create a Package library for this
https://github.com/elminson/barcode
Installation
composer require elminson/barcode
Basic use:
namespace Elminson\BarCode;
require_once(__DIR__ . ‘/vendor/autoload.php’);
$barcode = new BarCode(‘code128’);
$barcode->setText(“Testing”);
$barcode->setPrint(true);
$barcode->setTextColor(“#ff9900”);
$barcode->setBgColor(“#cccccc”);
$barcode->setFileName(“test”);
$barcode->setFilepath(__DIR__.”/temp/”);
$barcode->generate();
$barcode->SaveBarcodeToDisk();
$bardode->DestroyBarcode();
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 http://joxi.ru/brRGZRghJPDgMm 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?
I found this library based on this article:
https://github.com/elminson/barcode
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,
David