Generating QR Codes

If any of you have messed around with the google chart API you may or may not have come across an issue where the image returned from Google has no mime type.  Most browsers are smart enough to not care, but we would like our headers please where at all possible. So I made a QR action in my DownloadController:

public function qrAction()
{
   $target = $this->getRequest()->getParam('target');
   $saveas = $this->getRequest()->getParam('save');
   $dim = $this->getRequest()->getParam('dim');
   if(!isset($dim)){$dim = 200;}

   // disable view and layout 
   Zend_Layout::getMvcInstance()->disableLayout(); 
   $this->_helper->viewRenderer->setNoRender(); 
 
   $url = 'https://chart.googleapis.com/chart?';
   $params = array(
   'cht'=>'qr',
   'chs'=> $dim.'x'.$dim,
   'chl'=>$target
   );

   $url .= http_build_query($params);
   header ("Content-Type: image/png");
   if(isset($saveas))
   {
       header("Content-Disposition: attachment; filename=$saveas.png"); 
   }
   $content = file_get_contents($url); 
   echo $content;
}

As you can see, there are a couple of parameters that are accepted. Target is your target URL, and is the only required argument. A thing to note. Usually in Zend, we would usually access this like so:

http://example.com/download/qr/param/value/param/value

However as we are adding a url as a target the forward slashes mess this up, so we’ll use the old fashioned looking way of doing it:

http://example.com/download/qr?target=http://nasa.gov

This will give us our QR code with PNG headers as required 🙂 we can add dimensions to the url by adding:

http://example.com/download/qr?target=http://nasa.gov&dim=300

This will return a larger QR image. Finally, we can pass a filename to the saveas argument:

http://example.com/download/qr?target=http://nasa.gov&dim=300&saveas=nasa

which would bring up the save as dialog as nasa.png

Have Fun with your phone!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s