19 March 2013

create filter in controller symfony2

Sometimes you need to make changes to the Response object, after it is returned by your controller, but before it is rendered as output to the client (e.g. the browser). You may want to set some extra response headers, or "completely mess up the content" of the response. You can accomplish this by creating an event listener that listens to the kernel.response event. I give you a sample event listener which changes the Content-Type header in case the requested format is json and the browser’s accepted response format contains "text/html" in that case, at least in my experience, the browser doesn’t render the JSON string as plain text when the status code is 4xx or 5xx. So in these situations, the event listener changes the “Content-Type” to “text/plain”, to be sure you always get decent output in the browser.

Put the event listener in, for example /src/Acme/DemoBundle/EventListener/ResponseListener.php:

namespace Acme\DemoBundle\EventListener;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
class ResponseListener
    public function onKernelResponse(FilterResponseEvent $event)
        $request = $event->getRequest();
        // only do something when the requested format is "json"
        if ($request->getRequestFormat() != 'json') {
        // only do something when the client accepts "text/html" as response format
        if (false === strpos($request->headers->get('Accept'), 'text/html')) {
        // set the "Content-Type" header of the response
        $event->getResponse()->headers->set('Content-Type', 'text/plain');

Now define the ResponseListener as a service in /src/Acme/DemoBundle/Resources/services.xml:

<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
        <service id="acme.filter_response_listener" class="Acme\DemoBundle\EventListener\ResponseListener">
            <tag name="kernel.event_listener" event="kernel.response" method="onKernelResponse" />

Notice the “tag” tag, by which the kernel recognizes this service as an event listener. The event attribute tells the kernel which event this listener listens to. The “method” attribute tells which method should be called when the kernel.response event occurs.

In case you don’t want any other events to tamper with the Response, add a call to $event->stopPropagation().

15 March 2013

remove non ASCII characters from a String

Hi guys

I had a problem with removing non-utf8 characters from string, which are not displaying properly. Characters are like this 0x97 0x61 0x6C 0x6F (hex representation).

I am getting some encoded value from url. Let assume it's encoded email and value is ankitchauhan22@gmail.com
When I tried to find out the length of this string as
$email = somefunction($encodedStringFromUrl);
$length = strlen($email);
print $length;
I was shocked. It's printing 37 instead of 24. Than I printed each index of this string on the string but after 24 character, nothing printed.

I used trim() to remove whitespace but didn't work.

Then I tried something which worked for me.

This is a little snippet that will remove any non-ASCII characters from a string.
$string = "ankitchauhan22@gmail.com äó";
$string = preg_replace('/[^(\x20-\x7F)]*/','', $string);
Now It's printing 24.

13 March 2013

jQuery & JavaScript PDF Viewer plugin

Hi guys

In this Post I'm providing best jQuery PDF viewer plugin & tutorial with examples. Due to popularity of online document viewer like Google Docs some javascript developers develop a good and useful plugins to view pdf file on online pdf viewer.Here is some good list of online pdf viewers.

  1. JavaScript PDF Reader : pdf.js
    It's an HTML5 experiment that explores building a faithful and efficient PDF renderer without native code assistance.
    Read More Demo
  2. jQuery Media Plugin
    The jQuery Media Plugin supports unobtrusive conversion of standard markup into rich media content. It can be used to embed virtually any media type, including Flash, Quicktime, Windows Media Player, Real Player, MP3, Silverlight, PDF and more, into a web page and is compatible with all web hosting services The plugin converts an element which holds the object, embed iframe tags neccessary to render the media content.
    jQuery Media Plugin
  3. PDFObject : Embeds PDF files into HTML documents
    A JavaScript library for dynamically embedding PDFs in HTML documents. Modeled after SWFObject.
    Embeds PDF files into HTML documents
  4. Google Docs Viewer plugin for jQuery
    The Google Docs Viewer is an embeddable browser-based viewer that requires only a URL to a file available online. This neatly bypasses the need for users to have compatible software on their machines for those file types and displays the document right in the browser.
    Google Docs Viewer plugin for jQuery
  5. ZOHO Viewer plugin for jQuery
    The ZOHO Viewer is an embeddable browser-based viewer that requires only a URL to a file available online. This, just like Google Docs Viewer, bypasses the need for users to have compatible software on their machines for those file types and displays the document right in the browser. Automatically embeds the ZOHO viewer for viewing the doc, docx, xls, xlsx, ppt, pptx, pps, odt, ods, odp, sxw, sxc, sxi, wpd, pdf, rtf, txt, html, csv, tsv files it supports linked to by anchor tags.
    ZOHO Viewer plugin for jQuery
  6. jsPDF : Generate PDF files using pure client-side JavaScript
    It is an open-source library written by our lead developer, James, for generating PDF documents using nothing but JavaScript. You can use it in a Firefox extension, in Server Side JavaScript and with Data URIs in some browsers.
    jsPDF : Generate PDF files using pure client-side JavaScript
  7. jQuery Document Viewer
    Document Viewer is a jQuery plugin that allows you to view several file formats directly in a web page.
    jQuery Document Viewer
    Read More Demo

12 March 2013

css3 tips and tricks collection

You can never have too much of a good thing–and two good things we rely on in our work are tips and tricks. Nuggets of information, presented clearly and succinctly, help us build solutions and learn best practices.

CSS level 3 has been under development since December 15, 2005. CSS3 is modularized and consists of several separate recommendations. CSS3 is one of the more exciting and versatile developments for the web in some time. In this article I am going to create a huge list of CSS3 Tips, Tricks and Tutorials for Web Developers.

Useful Link : Be updated with these
  1. Featured Table Design With CSS3
  2. Basic CSS3 Techniques That You Should Know
  3. CSS3 Animated Bubble Buttons
  4. How To Create CSS3 Christmas Tree Ornaments
  5. Quick Tip : New HTML5 Form Features
  6. The State Of CSS3 In Email Templates
  7. CSS3 Transition Tutorial – Menü mit Slide-Effekt im Apple-Style
  8. Semantic CSS3 Lightboxes
  9. Creating A Realistic Looking Button With CSS3
  10. CSS3 Gradient Buttons
  11. Pure CSS3 Speech Bubbles
  12. Shadows And CSS3
  13. Dynamic PNG Shadow Position And Opacity
  14. Take Your Design To The Next Level With CSS3
  15. CSS3 Font-Face Or How To Use A Custom Font For Your Website
  16. CSS3 Fundaments – CSS3 Transitions
  17. Design A Prettier Web Form With CSS3
  18. Create A Sticky Note In 5 Easy Steps With CSS3 And HTML5
  19. Quick Tip : The Multi Column CSS3 Module
  20. Exciting Functions And Features
  21. Quick Tip : Understanding CSS3 Gradients
  22. How To Create Inset Typography With CSS3
  23. Build Awesome Practical CSS3 Buttons
  24. The State Of CSS3
  25. CSS3 Gradients : Quick Tutorial
  26. Easy And Fast CSS3 Techniques For Faux Image Cropping
  27. Understanding The Basics Of CSS3
  28. CSS3 Solutions for Internet Explorer
  29. How To Use CSS3 Orientation Media Queries
  30. CSS3 Transitions – Are We There Yet?
  31. Create A Color Changing Website Using CSS3
  32. Photoshop Effect vs CSS3 Properties
  33. 10 Awesome CSS3 Techniques To Improve Your Design
  34. Cross- Browser Rounded Buttons With CSS3 And jQuery
  35. Stylize Input Element Using CSS3
  36. Contextual Slideout Tips With CSS3 And jQuery
  37. Push Your Web Design Into The Future With CSS3
  38. A Look At Some Of The New Selectors Introduced In CSS3
  39. CSS3 Cheat Sheet (Pdf)
  40. Super Awesome Buttons With CSS3 And RGBA
  41. CSS3 Border Radius Property
  42. Overview Of CSS3 Structural Pseudo- Classes
  43. Sweet Ajax Tabs With jQuery And CSS3
  44. 3D Ribbons Only Using CSS3
  45. Text Rotations With CSS3
  46. Old School Clock With CSS3 And jQuery
  47. Editable CSS3 Image Gallery
  48. Drop Down Menu Tutorial
  49. Multiple Columns
  50. Multiple Backgrounds
  51. Create The Accordion Effect With CSS3
  52. CSS3 Opacity
  53. Create A Polaroid Photo Viewer With CSS3 And jQuery
  54. Sweet Tabbed Navigation Bar Using CSS3
  55. Rounded Corner Boxes
  56. A Crash Course In Advanced CSS3 Effects
  57. Halftone Navigation Menu With CSS3 And jQuery
  58. Awesome Overlays In CSS3
  59. Fancy Web Form With Field Hints Using Only CSS3
  60. CSS3 Gradients : No Image Aqua Button
  61. Box Shadows
  62. How To Use CSS3 Orientation Media Queries
  63. A Handful Of CSS3 Trends And How To Use Them
  64. The CSS3 Flexible Box Model
  65. Selectors Introduced In CSS3
  66. Create A Beautiful Looking Custom Dialog Box With jQuery And CSS3
  67. Get The Best Out Of CSS3
  68. Fundamental Problems With CSS3
  69. Pretty CSS3 Buttons
  70. Going Nuts With CSS3 Transitions

11 March 2013

speed up symfony2 application with varnish

Hi everyone,

Just a quick note about Varnish integration for symfony. I’m sure you have heard of Varnish reverse proxy server.
Varnish is a web accelerator written with performance and flexibility in mind. It’s modern architecture gives it a significantly better performance than many of it’s competing products. Varnish store web pages in memory so the web servers don’t have to create the same web page over and over again. The web server only recreate a page when it is changed. Additionally Varnish can serve web pages much faster then any application server is capable of – giving the website a significant speed up.
So in first order you may be interested to integrate Varnish to handle pages which don’t require authentication (for myself I’m still not sure if there is any advantage for integrating pages for logged in users):
sub vcl_recv {
    set req.http.Surrogate-Capability = "abc=ESI/1.0";
sub vcl_fetch {
    if (beresp.http.Surrogate-Control ~ "ESI/1.0") {
        unset beresp.http.Surrogate-Control;
        set beresp.do_esi = true;
Symfony2's cache uses the standard HTTP cache headers, the Symfony2 Reverse Proxy can easily be replaced with any other reverse proxy. Varnish is a powerful, open-source, HTTP accelerator capable of serving cached content quickly and including support for Edge Side Includes.

08 March 2013

Creating a PrestaShop module

A PrestaShop module consists of:
  • A root folder, named after the module, which will hold all of the module's files, and will reside in PrestaShop's /modules folder.
  • A main PHP file, named after the module, located in that root folder. This PHP file should have the same name as its root folder.
  • An icon file, named logo.gif, representing this module.
  • Optional: some .tpl files, containing the module's theme.
  • Optional: language files, if the module or its theme have text to display (and therefore, that should be translatable).
  • Optional: in a /themes/modules folder, a folder with the same name as the module, containing .tpl and language files if necessary. This last folder is essential during modifications of existing module, so that you can adapt it without having to touch its original files. Notably, it enables you to handle the module's display in various ways, according to the current theme.
Now I am going to create a module named Testmodule.

Your module can be called anything you like. My module will be called Testmoduleas that is what is will be doing - taking off line payments. So create a directory under your PrestaShop.

C:\wamp\www\prestashop\modules\Testmodule see below for an example:-
prestashop folder

Create your module's "class" .php file

PrestaShop modules must have one php file which contains the Class definition. This class definition contains the core functions of your module. The file needs to be given the same name as your module so in my case it must called testmodule.php and it needs to live in the root of the modules directory.

Every PrestaShop module has to consist of three necessary functions:
  1. __construct() – here you provide all the information about your module – module name, version and description which are visible in the backend. In addition, you can choose in which tab to show your module, for example, Products.
  2. install() – this function also does not have parameters, but is very important. Here you have to register all the hooks you will be using, create necessary database table changes (create, add columns, prepare it and so on) and initiate default module options.
  3. uninstall() – the same as above, except here you have to delete all your tables if necessary. Do not forget to delete configuration options too.
class TestModule extends SomeModule  {

 //this declares the class and specifies it will extend the some module

    private $_html = '';
    private $_postErrors = array();
    function __construct()
        $this->name = 'testmodule';
        $this->tab = others;
        $this->version = 1;
        $this->author = 'Ankit Chauhan';

        parent::__construct(); // The parent construct is required for translations
        $this->page = basename(__FILE__, '.php');
        $this->displayName = $this->l('Test Module');
        $this->description = $this->l('Testing module check');
    function install()
      // your code here
    function unstall()
      // your code here

Now you can upload everything to your server and install module from the backend.

01 March 2013

Styling Progress Bar With HTML5


HTML5 introduced the progress bar element, which allows us to show the progress of certain tasks, like uploads or downloads, basically anything that is in progress

progress bar

Basic Usage

The progress bar can be added with <progress>; the progress value is determined with the value, min and max attributes, as follows.
<progress value="40" max="100"></progress>  

Since this is a native progress bar, the presentation is vary dependent on the platform. Below is how a native progress bar looks in Windows and OSX.

Now, let's try styling this progress bar, so it has a consistent or similar look across all platform.

Styling Progress Bar

In the stylesheet, we actually can use the element selector to target and add style rules to <progress> element. In this example, we change the background color, remove the border line, and make it rounded by adding a border radius at half of its height.
progress {  
    background-color: #f3f3f3;  
    border: 0;  
    height: 18px;  
    border-radius: 9px;  
However, each browser handles this a bit differently.

In Firefox, the styles affect the progress bar, while the progress meter / value is not affected.

In Chrome and Safari, it will remove the native styles and presentation from the platform and replace it with the Webkit stylesheet, the styles above will not be applied (at least, at the moment).

So, we need some more workaround in these cases.
progress style

In Chrome and Safari, the progress element is translated this way.
    ┗ <div>  ::-webkit-progress-bar  
         ┗ <div> ::-webkit-progress-value 
Thus, to change the progress bar and the progress value styles in these browsers, we need to add those Webkit pseudo-classes.
progress::-webkit-progress-bar {  
    /* style rules */  
progress::-webkit-progress-value {  
    /* style rules */  
Firefox also has its special pseudo-class that is ::-moz-progress-bar. Unlike Chrome and Safari, this pseudo-class in Firefox refers to the progress meter/value.
progress::-moz-progress-bar {  
    /* style rules */  
To conclude, these are currently the entire selectors for styling HTML5 progress bar.
progress {  
    /* style rules */  
progress::-webkit-progress-bar {  
    /* style rules */  
progress::-webkit-progress-value {  
    /* style rules */  
progress::-moz-progress-bar {  
    /* style rules */  

Animate The Progress

Next, we will see how to animate the progress bar. Typically, the progress bar expands from left to right as the task progresses.

The idea is, the progress bar will expand from 0 and stop once it reaches the maximum value. We will also display the value number as it is progressing. Below is the HTML structure.

<progress id="progressbar" value="0" max="100"></progress>    


In this example, we will use jQuery to animate the progress bar. So, we should also not forget to insert the jQuery, like so.
<script src="path_to_folder/jquery.js" type="text/javascript"></script>  
Then, we add the scripts to make the progress bar expand. First, we store the progress bar element, the progressbar value as well the maximum value, and the timeframe, in Variables.
var progressbar = $('#progressbar'),  
    max = progressbar.attr('max'),  
    value = progressbar.val(),  
    time = (1000/max)*5;   
Next, we create a variable that store the animation function. In this example, we call the variable loading.
var loading = function() {  
Inside the above function, we set the progress interval. We will increase the value by 1 per timeframe — you can increase the value to make the progress run faster.
value += 1; 
And then, we add the result to the progress bar.
addValue = progressbar.val(value);  
We also show the value inside, next to the progress bar.
$('.progress-value').html(value + '%');  
Next, we create a new function to run the animation function.
setInterval(function() {  
}, time);  
At this point, the animation is already functioning. However, the value will keep increasing infinitely. So, we need to create a conditional statement for the animation to stop when it reaches its maximum value.
First, let's store the above function in a variable like so.
var animate = setInterval(function() {  
And, inside the loading variable, we add the conditional statement, as follow.
if (value == max) {  
The above script states that once the value is equal to the maximum value, clear the interval, which will stop the animation function.
That's it and here are all the codes to animate the progress bar.
$(document).ready(function() {  
    var progressbar = $('#progressbar'),  
        max = progressbar.attr('max'),  
        time = (1000/max)*5,      
        value = progressbar.val();  
    var loading = function() {  
        value += 1;  
        addValue = progressbar.val(value);  
        $('.progress-value').html(value + '%');  
        if (value == max) {  
    var animate = setInterval(function() {  
    }, time);  

27 February 2013

creating stick stylish button using css3

CSS3 is rapidly expanding the toolkit that web developers and designers have to make visually appealing components without the use of images, Photoshop, or CSS sprites. While all of those have their place, and will never be completely removed from the development process, buttons are one component of a website that we can make dynamic, slick and scalable – exclusively in code.

All of the CSS3 buttons that we create today will be styled forms of anchor tags. Some like to use button elements for these, but I find it’s easiest to use anchor tags so you can easily add the :hover and :active pseudo classes and quickly add href to it to complete the button.

What We're Creating

For this tutorial, we’ll be creating several different CSS3 buttons, all of which can have different colors, shadows, sizes – all using pure CSS3. We will be using the following properties: border-radius, linear-gradient, box-shadow, text-shadow and opacity. you might want to change some of these to fit your purpose, and for light colored buttons, a different color would likely be a wise choice. But that’s for you to decide.
    padding: 6px 12px;
    margin: 4px;
    color: #fff;
    font-family: "Helvetica Neue", Arial, sans-serif;
    font-size: 12px;
    text-shadow: 1px 1px 2px #000;
    text-decoration: none;
    font-weight: bold;

Creating the Gradient Class

In order to maintain our sanity when working in stylesheets, we’ll create a .gradient class that we can attach to any of our buttons. This uses CSS3's linear-gradient and opacity to create a dynamic background that will give the effect of a gradient to practically anything you attach it to, allowing the background color to shine through.

To someone that hasn’t looked at a lot of CSS3 markup, this code may look daunting, but I assure you, it’s not. If you want to brush up on your properties syntax and browser prefixes (those -moz, -webkit, -o things you see here), check out.
.gradient {
    background-image: -moz-linear-gradient(rgba(0,0,0,0.1), rgba(0,0,0,0.3));
    background-image: -webkit-linear-gradient-webkit-gradient(linear, 0% 0%, 0% 100%, from(rgba(0, 0, 0, 0.1)), to(rgba(0, 0, 0, 0.3)));
    background-image: -webkit-linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.3));
    background-image: -o-linear-gradient(rgba(0, 0, 0, 0.1)), to(rgba(0, 0, 0, 0.3));
    background-image: -ms-linear-gradient(rgba(0, 0, 0, 0.1)), to(rgba(0, 0, 0, 0.3));
    background-image: no-repeat;
    border: 1px solid rgba(0, 0, 0, 0.2);
.gradient:hover {
    background-image: -moz-linear-gradient(rgba(0,0,0,0), rgba(0,0,0,0.2));
    background-image: -webkit-linear-gradient-webkit-gradient(linear, 0% 0%, 0% 100%, from(rgba(0, 0, 0, 0)), to(rgba(0, 0, 0, 0.2)));
    background-image: -webkit-linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.2));
    background-image: -o-linear-gradient(rgba(0, 0, 0, 0)), to(rgba(0, 0, 0, 0.2));
    background-image: -ms-linear-gradient(rgba(0, 0, 0, 0)), to(rgba(0, 0, 0, 0.2));
    background-image: no-repeat;
    border: 1px solid rgba(0, 0, 0, 0.2);
.gradient:active {
    background-image: -moz-linear-gradient(rgba(0,0,0,0.2), rgba(0,0,0,0));
    background-image: -webkit-linear-gradient-webkit-gradient(linear, 0% 0%, 0% 100%, from(rgba(0, 0, 0, 0,2)), to(rgba(0, 0, 0, 0)));
    background-image: -webkit-linear-gradient(rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0));
    background-image: -o-linear-gradient(rgba(0, 0, 0, 0.2)), to(rgba(0, 0, 0, 0));
    background-image: -ms-linear-gradient(rgba(0, 0, 0, 0.2)), to(rgba(0, 0, 0, 0));
    background-image: no-repeat;
    border: 1px solid rgba(0, 0, 0, 0.2);
The :hover pseudo class changes the opacity at the top from 10% to 0% and at the bottom of the gradient from 30% to 20%, giving it a highlighted look. Finally, the :active pseudo class flips the gradient (making it darker at the top, and lighter at the bottom), giving it a nice depressed look.

Adding a Splash of Color

We've got the anchor tag and the gradient classes, now let's add some color to our buttons. This is where the true beauty of our linear-gradient with opacity shines through absolutely intended.

For my colors here, I’m just going to hop on to Kuler and grab five vibrant colors. Let’s create classes and specify the background-color property to that color.
The CSS:
/*--- The Colors ---*/
.red { background-color: #F20C0C; }
.green { background-color: #30AC04; }
.blue { background-color: #0F9BF2; }
.pink { background-color: #FD13DC; }
.yellow { background-color: #FEF95B; }

The markup:
<a href="#" class="button red gradient">This is a Red Button</a>
<a href="#" class="button green gradient">This is a Green Button</a>    
<a href="#" class="button blue gradient">This is a Blue Button</a>
<a href="#" class="button yellow gradient">This is a Yellow Button</a>
<a href="#" class="button pink gradient">This is a Pink Button</a>
See the example here

This is a Red Button
This is a Green Button
This is a Blue Button
This is a Yellow Button
This is a Pink Button

Rounding the Corners

The border-radius property is one of the widely adopted CSS3 properties that almost all modern browsers use (except, of course, for Internet Explorer 8 and previous). iOS Safari and older versions of Safari and Firefox still use the -webkit and -moz prefixes, so we'll use them here to insure compatibility. CanIUse’s support grid shows 61.1% support across users. That number should continue to rise as the most updated version of every major browser supports border-radius and our code gracefully degrades to display the nice box button in the previous example.

Leveraging the flexibility of classes, we’ll create three classes for rounded corners, which gives you flexibility when deciding how you want your button to look.
.large-corners { 
    border-radius: 20px;
    -moz-border-radius: 20px;
    -webkit-border-radius: 20px 20px;
.medium-corners {
    border-radius: 12px;
    -moz-border-radius: 12px;
    -webkit-border-radius: 12px 12px;
.small-corners {
    border-radius: 6px;
    -moz-border-radius: 6px;
    -webkit-border-radius: 6px 6px;

So by simply attaching these classes to your buttons, you can quickly switch between a button with large 20px rounded corners, to one with small 6px corners, or leave the class off all together and get a button with square corners. Plus, throwing the color classes in there (and the ability to make more color classes) gives you a complete tool set to create an unlimited number of buttons.
<a href="#" class="button green gradient">This is a Green Button</a>    
<a href="#" class="button blue gradient  small-corners">This is a Blue Button</a>
<a href="#" class="button yellow gradient medium-corners">This is a Yellow Button</a>
<a href="#" class="button pink gradient large-corners">This is a Pink Button</a>
This is a Green Button
This is a Blue Button
This is a Pink Button
This is a Yellow Button

Dynamic Sizing

The greatest part about using CSS3 to create your buttons is the freedom it allows you to change things up on the fly. No more firing up Photoshop every time you want to create a larger button for an emphasized call to action, or a smaller button to link to the rest of a story. To create different buttons here, simply create different classes, with varying text size. Since the .button class already has a padding of 10px on the top and bottom and 20px on the left and right, the gradient button will automatically resize.

For this example, I've created four new classes (.button-small, .button-medium, .button-large, and .button-xlarge) and simply altered the font-size property. Additionally, to keep the visuals looking good, I've altered the padding on the smaller two buttons, so the button size doesn't overwhelm the call to action (the text).
.button-small {
    font-size: 10px;
    padding: 5px 10px !important;
.button-medium {
    font-size: 12px;
    padding: 8px 12px !important;
.button-large {
    font-size: 16px;
.button-xlarge {
    font-size: 24px;

To activate these classes, simply attach them to the anchor tags in your code.
<a href="#" class="button gradient green button-small">This is a small button</a>
<a href="#" class="button gradient blue button-medium">This is a medium button</a>
<a href="#" class="button gradient pink button-large">This is a large button</a>
<a href="#" class="button gradient yellow button-xlarge">This is a XL button</a>
This is a small button
This is a medium button
This is a large button
This is a XL button

Drop that Shadow

Time to make another class. Getting sick of them yet? It may seem like a lot, but when you think about the flexibility that it provides you to literally be able to have any type of button on your website, a little leg work in the stylesheet pays off.

So we’ll create a .shadow class with the CSS3 box-shadow property. For details on this property, check out CSS3Files.com.
.shadow {
    box-shadow: 0px 0px 4px 2px #aaa;
    -webkit-box-shadow: 0px 0px 4px 2px #aaa;
    -moz-box-shadow: 0px 0px 4px 2px #aaa;
<a href="#" class="button pink gradient medium-corners button-xlarge shadow">This is a Pink Button</a>
This is a Pink Button

A Gradient Twist

Another popular method of using gradients is to make the background come to a ‘point’ in the middle. This is done by using the linear-gradient property with a 50% stop. For these, you will need to specify specific colors.
.alt-gradient {
    background-color: #ee432e;
    background-image: -webkit-gradient(linear, left top, left bottom, from(#ee432e 0%), to(#c63929 50%));
    background-image: -webkit-linear-gradient(top, #ee432e 0%, #c63929 50%, #b51700 50%, #891100 100%);
    background-image: -moz-linear-gradient(top, #ee432e 0%, #c63929 50%, #b51700 50%, #891100 100%);
    background-image: -ms-linear-gradient(top, #ee432e 0%, #c63929 50%, #b51700 50%, #891100 100%);
    background-image: -o-linear-gradient(top, #ee432e 0%, #c63929 50%, #b51700 50%, #891100 100%);
    background-image: linear-gradient(top, #ee432e 0%, #c63929 50%, #b51700 50%, #891100 100%);
    border: 1px solid #951100;
Another Button

Breaking the Mold: Adding 3D Depth

Now is when we start to experiment a little bit more. By using the box-shadow property and defining multiple shadows separated by a comma, we can add an inset box-shadow (like an Inner Shadow in Photoshop), a light shadow on the top and sides, and a deep shadow below. While this may not look like much, when you "erase" that deep shadow, while offsetting it with some margin and padding, you really get the effect of a 3-dimensional button that you’re pushing down. Check it out.
.push {
    box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
    -webkit-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
    -moz-box-shadow: inset 0 1px 10px 1px #5c8bee, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111;
    display: inline-block;
    margin-bottom: 10px
    padding: 10px 0 12px 0;
.push:hover {
    box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111 !important;
    -webkit-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111 !important;
    -moz-box-shadow: inset 0 0px 20px 1px #87adff, 0px 1px 0 #1d2c4d, 0 6px 0px #1f3053, 0 8px 4px 1px #111111 !important;
.push:active {
    box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111 !important;
    -webkit-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111 !important;
    -moz-box-shadow: inset 0 1px 10px 1px #5c8bee, 0 1px 0 #1d2c4d, 0 2px 0 #1f3053, 0 4px 3px 0 #111111 !important;
    margin-top: 8px;
Another Button

21 February 2013

Controllers as Services in Symfony2

Controller as a service is continually touted as the best practice.

But why would I wrap a controller into a service? That's good question.

Well, the point of doing this in general is not having to inject the DI container into your controllers (instead, you inject the dependencies into the controller directly). Thus the controller no longer depends on the container.
  1. Good: You get added flexibility. You no longer hard-code which services to use into your controller. You can specify that in the DI configuration instead. Example: You inject a UserProvider into the UserController for /profile, but inject a FacebookUserProvider into the same UserController for /profile/facebook.
  2. Bad: You must manually configure your dependencies in the DIC config. You need to manually assign the injected dependencies. Optional dependencies are no longer lazy-loaded.
This is basically just a proof of concept to show how it could be done.
namespace Acme\DemoBundle\Controller;

class FooController
    public function __construct($container, ...)
        $this->container = $container;
        // ... deal with any more arguments etc here

    public function foo($params)
        // ...
        return $x;

    protected function get($service)
        return $this->container->get($service);

Ditto for the bar() and something() methods, each in their own controller. Then, add them to your application as a service. Eg in your config.yml (other methods available):
        class: Acme\FooBundle\Controller\FooController
            container: "@service_container"

See the Symfony docs for more details about how you can construct this entry, including injecting any dependencies such as an entity manager or similar. Now, you can get an instance of this from the container:
public function yourMainAction()
    // ...

    $newData = $this->get("my.foo.service")->fooAction($someData);

    // ...

    return new Response(json_encode($newData), ...);

Likewise again for BarController and SomethingController. The advantage now is that this service can be made available at any point in your application (whether via the container as above, or as an injected service), across bundles, without needing to instantiate the class manually yourself and provide any dependencies.

20 February 2013

run symfony command from controller

Hi Friends,
Few month back I was trying to execute Symfony2 command in my controller. See how can we do that.

Step 1

Register you command as service
    class: MyBundle\Command\MyCommand
        - [setContainer, ["@service_container"] ]

Step 2

In your controller, you'll just have to get this service, and call the execute method with the rights arguments. Set the input with setArgument method:
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
public function myAction() {
  $command = $this->get('MyCommandService');
  $input = new ArgvInput(array('arg1'=> 'value'));
  $output = new ConsoleOutput();
  $command->run($input, $output);

Step 3

Either you can use the execute method of command:
$command->execute($input, $ouput);
But see the defination of run() and execute() methods.

  • run () -: The code to execute is either defined directly with the setCode() method or by overriding the execute() method in a sub-class. 
  • execute () -: This method is not abstract because you can use this class as a concrete class. In this case, instead of defining the execute() method, you set the code to execute by passing a Closure to the setCode() method.

19 February 2013

protecting php file with ionCube encoder

One of the issues PHP developers face is that PHP is an interpreted language, meaning PHP source code is readable by anybody who downloads your applications. In this article I will show you how to protect your intellectual property by encoding your PHP source code.

The tool we are going to use to protect our code is ionCube PHP Encoder. Before releasing your PHP software, you use the encoder to convert your plain-text PHP files into special encrypted files.While ionCube PHP Encoder is a commercial product, there is a time-limited trial available for download.

Because your PHP is encoded into a special byte-code (as opposed to just being obfuscated), a loader must be installed on your web server. A loader is a PHP module that must be installed. Fortunately, ionCube PHP Encoder is commonly used and therefore many web hosts will already have a loader installed.

On the ionCube website there is a loaders page which contains the latest versions of the loader for all supported platforms (you must install the correct loader for your platform). You will need the loader for your platform installed in order to be able to run code you encode from this article.

Before we proceed, let's take a quick look at an encoded file. Snippet 1 shows a basic PHP script.
Snippet 1
    echo "Hello, world!\n";

We can then run this script through the encoder. While there are many different options available, encoding a script with the default options yields the following PHP file.
Snippet 2
<?php //000a8
echo('Site error: the file '.__FILE__.' requires the ionCube PHP Loader '.
basename($__ln).' to be installed by the site administrator.');exit(199);

While you cannot understand what this code does just by looking at it, your PHP installation with the correct loader installed interprets this just as if it was the code in Snippet 1.

Encoding Your PHP Files

The ionCube PHP Encoder is a command-line script you run either one or more files, or on an entire set of folders. If you're encoding an entire PHP application you would typically run it on the original source folder. The encoder will duplicate the entire tree, except the PHP code will be encoded.

In the previous section I showed you what the encoded PHP code from a basic "Hello World" script looks like. The command I used to generate this encoded script is as shown in Snippet 3
Snippet 3
/usr/local/ioncube/ioncube_encoder5 helloworld.php -o helloworld-enc.php

In this example, the -o specified the output location. In this example I just created the encoded file in the same directory with a different filename. Typically you would want to create the file with the same filename as the original (without replacing the original source code).

To achieve this, set the input and output both to be a directory. The encoder will automatically recurse through all directories in the input directory and encode all PHP files.

To demonstrate this, let's assume helloworld.php is in a directory called src. Snippet 4 shows the command we use to encode this entire path. The example outputs the encoded files to the build directory.
Snippet 4
/usr/local/ioncube/ioncube_encoder5 src -o build

Protecting Non-PHP Code

Depending on how your web application has been designed, there may be some non-PHP files you would to prevent users from being able to read. A good example of such files is XML files or Smarty template files.
The ionCube PHP Encoder includes an encryption option. This feature is used to protect non-PHP files (but it differs from the PHP encoding since the output isn't a bytecode format format).

To encrypt files, the --encrypt command-line option is used. You can then specify a file pattern that will be encrypted. For example, if you want to encrypt every file with extension tpl you would specify --encrypt "*.tpl". Without doing so, the encoder would simply copy all tpl files exactly as-is into the target directory.

Snippet 5 shows the command we can now type on our src directory. The directory contains the helloworld.php script and a template called index.tpl.

Snippet 5
/usr/local/ioncube/ioncube_encoder5 src/ -o build --encrypt "*.tpl"

Your application must be able to handle these encrypted files. Fortunately, when a loader is present in a PHP installation, a number of additional functions are made available that allow you to deal with encrypted files.

The ioncube_read_file() will decrypt files that have been previously encrypted. This function accepts a filesystem path as its only argument and will return the decrypted data. If the input path was not encrypted it will be returned as-is.


In this article I showed you how you can protect your PHP code using the ionCube PHP Encoder. While I only showed your the absolute basics, there are many other features available with the encoder that make it ideal for projects of all sizes.

Some of those features include:
  1. Adding a licensing mechanism to your code so only license-holders can use your code
  2. Handling various events in the loading process (such as if the loader isn't found)
  3. Writing custom properties to an encoded file

18 February 2013

multiple cron job using same file

Hi guys, Today I am posting something about cron. 1 year back, I was getting some trouble in my project in scheduling cron. I had lots of task to be managed by cron, for that I was making multiple files. But after some research I managed those task by a single file.

If your cron job accomplish similar tasks or requires the same libraries you will have to include the same files over and over to all your cronjobs ... or use this solution.

Let say you have these cron jobs:
0 1 * * * /etc/lib/php -q /home/user/cron/cron1.php
15 1 * * * /etc/lib/php -q /home/user/cron/cron2.php
30 1 * * * /etc/lib/php -q /home/user/cron/cron3.php
0 2 * * * /etc/lib/php -q /home/user/cron/cron4.php

And each of these cron jobs perform different tasks but use the same libraries like phpmailer, pdf creator, geoip, payment verification etc...

The idea is simple, separate tasks or commands using parameters:
0 1 * * * /etc/lib/php -q /home/user/cron/cron1.php --task=task1
15 1 * * * /etc/lib/php -q /home/user/cron/cron2.php --task=task2 --filter=cron3
30 1 * * * /etc/lib/php -q /home/user/cron/cron3.php --task=task3 --param=cron3
0 2 * * * /etc/lib/php -q /home/user/cron/cron4.php --task=task4

In order to accomplish this, the main cronjob file will required the following PHP code:
function getArguments() {
  $argument = array();
  for($i = 1; $i < $_SERVER['argc']; ++$i) {
    if(preg_match('#--([^=]+)=(.*)#', $_SERVER['argv'][$i], $reg)) {
      $argument[$reg[1]] = $reg[2];
  return $argument;

$argv = getArguments();

Then in your cron.php simply use this code to separate tasks or commands:
// include libraries

if($argv['task'] == 'task1') {
  // do task
elseif($argv['task'] == 'task2') {
// etc...

15 February 2013

connect to multiple database from drupal

Drupal has the ability to connect to multiple databases, allowing you to use Drupal’s built in database abstraction layer on more than just Drupal's primary database.

Preferably you would add your configuration in the settings.php file for your site, so that all modules can interact with the new database.

Drupal 7

In your settings.php:

$databases = array();
$databases['default']['default'] = array(
  // Drupal's default credentials here.
  // This is where the Drupal core will store it's data.
$databases['alternate_db']['default'] = array(
  // Your secondary database's credentials here.
  // You will be able to explicitly connect to this database from your modules.

The way to use it in module:

// Use the database we set up earlier

// Run some queries, process some data

//Switch back to the default connection when finished.
// otherwise Drupal will not be able to access it's own data later on.

You can setup databases on the fly when you need it

If only one of your module is using alternate database, you can define the connection directly there in module as:

$alternate_db = array(
    'database' => 'databasename',
    'username' => 'username',
    'password' => 'password',
    'host' => 'localhost',
    'driver' => 'mysql',
// replace 'AlternateDatabaseKey' with something that's unique to your module
Database::addConnectionInfo('AlternateDatabaseKey', 'default', $alternate_db);

// execute queries here

db_set_active(); // without the paramater means set back to the default for the site
drupal_set_message(t('The queries have been made.'));

If you are using Drupal 6 or older version of Drupal than it's little different. You can use it by editing $db_url string in configuration file (setting.php of conf.php). There is by default single connection is defined.

$db_url['default'] = 'mysqli://user:password@localhost/drupal';

// you can add another connection as
$db_url['alternate_db'] = 'mysqli://user:password@localhost/alternate_db';

To query a different database, simply set it as active by referencing the key name.

// Use the database we set up earlier

// Run some queries, process some data

//Switch back to the default connection when finished.
// otherwise Drupal will not be able to access it's own data later on.

14 February 2013

create and execute a command in symfony 2

In Symfony 1.x a task is a command line tool to help perform tasks around the application. The same is in Symfony 2. Unfortunately in Symfony2 there is no tool to auto-generate some code for these. To create a Symfony2 Command you must to have or to create in your Bundle a folder named Command.

Symfony 2 is mainly used to create web application, however, sometimes you need to extend your app and need a command line tool to help perform tasks around the application.

It's one of the most stable parts of the framework and many people have already been using it for several months in many projects as it makes it really easy to develop this kind of software. And of course, everything is done in a really cool way, as many of the parts of Symfony2.

Let’s see how can extremely easy create a new Command Task and custom our output.

Create a file in Command Folder, for instance NewsletterCommand.php and fill it with an empty Command structure as follows

namespace Ankit\NewsletterBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class NewsletterCommand extends ContainerAwareCommand
    protected function configure()
            ->setDescription('Sends our daily newsletter to our registered users')
    protected function execute(InputInterface $input, OutputInterface $output)
        $output->writeln('Starting Newsletter process');
You can execute it as:

app/console send:newsletter
The output will be as:
Starting Newsletter process
You can pass some arguments form command too. Lets see how

//addArgument in configure() as 
            ->setDescription('Sends our daily newsletter to our registered users')
            ->addArgument('region', InputArgument::OPTIONAL, 'Where to send?')
//and get this argument in execute() as
       $region = $input->getArgument('region');
       $output->writeln('Sending newsletter to '.$region.' region');
You can execute it as:

app/console send:newsletter India
The output will be as:
Starting Newsletter process
Sending newsletter to India region
Unlike arguments, options are not ordered (meaning you can specify them in any order) and are specified with two dashes (e.g. --India - you can also declare a one-letter shortcut that you can call with a single dash like -I).

Symfony2 will automatically locate and include the command as part of the console commands.

13 February 2013

how to use claim token in technorati

It's very easy to verify your blog using claim token in technorati.

although technorati doesn’t show you how to claim your token to verify your blog in technorati. Here I’m going to tell you how to verify your blog listing in technorati using claim token.

after creating an account in technorati, you recieve a mail having the text following from them.

This is an automatically-generated email.

Thank you for submitting your blog claim on Technorati. Technorati will need to verify that you are an author of the site http://ankitchauhan22.blogspot.in by looking for a unique code. We have just assigned the claim token ############## to this claim. Please visit http://technorati.com/account/ for more details, including how to use the claim token.

Follow these steps to verify your blog using claim token.
  1. Create a new post (such as this) using your blog panel.
  2. Copy the claim code from your email.
  3. Paste your 12-digit technorati claim token in the body of the post.
  4. Your blog will be verify by following these steps
After the verrification, you will recieve an mail from technorati saying something like this.

Thank you for submitting your blog claim on Technorati. We have successfully crawled your blog and found the claim token, and your claim is now awaiting review.

My Technorati Claim Token : XXXXXXXXXXXX

Message after claiming Token:-

We have successfully crawled your blog and found the claim token, and your claim is now awaiting final review. You may now remove the claim token from your feed.

The final message by technorati

This is an automatically-generated email.

Congratulations, your claim is now complete! Please allow 24 to 48 hours for Authority and recent posts to begin showing for your site now that it has been successfully claimed. Once they are there, we will update your site's Authority once per day.

At first you may not see your site listed in the Technorati Blog Directory for all of the categories you've selected. As you write blog posts around those topics, you should see your Topical Authority in those categories begin to rise.

18 January 2013

create subdomains using htaccess

Its very quick and easy. Here we go

  1. You need to create a wildcard domain on your DNS server *.website.com 
  2. Then in your vhost container you will need to specify the wildcard aswell *.website.com - This is done in the ServerAlias DOCs 
  3. Then extract and verify the subdomain in PHP and display the appropriate data
Here we go in some detail.
  • Create a wildcard DNS entry - In your DNS settings you need to create a wildcard domain entry such as *.example.com. A wildcard entry looks like this:
     *.example.com.   3600  A
  • Include the wildcard in vhost - Next up in the Apache configuration you need to set up a vhost container that specifies the wildcard in the ServerAlias DOCs directive. An example vhost container:
      ServerName server.example.com
      ServerAlias *.example.com
      UseCanonicalName Off
  • Work out which subdomain you are on in PHP - Then in your PHP scripts you can find out the domain by looking in the $_SERVER super global variable. Here is an example of grabbing the subdomain in PHP:
    preg_match('/([^.]+)\.example\.com/', $_SERVER['SERVER_NAME'], $matches);
    if(isset($matches[1])) {
        $subdomain = $matches[1];
    I have used regex here to to allow for people hitting your site via www.subdomain.example.com or subdomain.example.com.
    If you never anticipate having to deal with www. (or other subdomains) then you could simply use a substring like so:
    $subdomain = substr(
                     $_SERVER['SERVER_NAME'], 0,
                     strpos($_SERVER['SERVER_NAME'], '.')
I did it in php. For java or dot net, you need to change my php code to respective java or dot net code.