Installing ImageMagick for PHP on Ubuntu

iMagick is a wrapper class, wrapping the most common web image manipulation actions in easy to use functions, but allowing full access to iMagick’s power by issuing system calls to it’s command-line programs. There is no proper documentation for Installing ImageMagick for PHP on Ubuntu or any other LINUX based systems. Here is some simple steps for enabling ImageMagick library to work with PHP. Also there is no need to worry for MagickWand. iMagick will do everything for you.

First of all remove everything you have tried to make it work. Uninstall iMagick with the following command:

sudo apt-get remove imagemagick

Remove ImageMagick and all its dependencies with the following command:

sudo apt-get remove –auto-remove imagemagick

Purge the config file of ImageMagick with the following command:

sudo apt-get purge imagemagick

Or similarly, like this:

sudo apt-get purge –auto-remove imagemagick

Well, all your previous installation files are just gone. Now Install it purely and perfectly without any conflict or file modification. Enter the following two commands:

sudo apt-get install imagemagick
sudo apt-get install php5-imagick

That was way too easy – thanks interwebs! Remember to restart/reload your webserver..

sudo service apache2 graceful

That’s all. Check your php.ini or test with any simple script. For simple scripts to test iMagick you can refer to this post.

How To Get Current Page URL In PHP

Sometimes, you might want to get the current page URL that is shown in the browser URL window. For example if you want to let your visitors submit a blog post to Digg you need to get that same exact URL. There are plenty of other reasons as well. Here is how you can get current url in php.

Following function will do everything for you,

You can now get the current page URL using the line:

Sometimes it is needed to get the page name only. The following example shows how to do it:

Happy Coding .. 🙂

Display Unsupported Image Formats In Browser

Most of the browsers do not support most of the image file types rather than some common file types like JPG, PNG and GIF. But in most of the web projects user need to upload some most used file types like PSD, PDF ( Unsupported image formats ) etc. and they need to see what they have uploaded is perfect or not.

So here are some methods using PHP and ImageMagick module for PHP to disply a little more formats in browsers by converting them into JPG format.

Displaying the JPG file format image in browsers :

Displaying the PNG file format image in browsers :

Displaying the GIF file format image in browsers :

The functions used above imagecreatefromjpeg(), imagecreatefrompng(), imagecreatefromgif(), imagejpeg() for reading .jpg, .png and .gif files are library functions of PHP. So so need not to bother about how to make them work.

Displaying the PSD file format image in browsers :

Here the function used i.e. imagecreatefrompsd() is not predefined library function. So in order to make it work we need to include an extra class file which will read the PSD files and gice the browser a JPEG file as output. You can download the classPhpPsdReader.php here.

Displaying the TIFF file format image in browsers :

Displaying the PDF file format image in browsers :

You need to call he wrapper class of ImageMagick inorder to make it work of pdf and tiff files. Follow the installtion guide of ImageMagick Here.

Scroll To Specific Section Using jQuery

We can scroll to specific section using jQuery method .scrollTop(). .scrollTop() expects a parameter, that is , the pixel value where the scroll bar should scroll to.

is able to scroll the window ( if there is enough content in it ). You can also get desired value with offset() and position().

This will scroll the contact element to view. The non-jQuery alternate method is .scrollIntoView(). You can call that method on any DOM element like:

true indicates that the element is positioned at the top whereas false would place it on the bottom of the view. The nice thing with the jQuery method is, you can even use it with functions like .animate(). So you might smooth scroll something.

you can use a very lightweight approach by defining your custom scroll jquery function.

Scroll to a page using coordinates,

scrolling with window.scroll,

only to sum up, use the window.location.hash to jump to element with ID,

Happy Coding 🙂

How To Set Up Apache Virtual Host on Windows


As a webmaster, upon creating your first site, you may want to install a program like XAMPP. You then put your site in the /htdocs/ directory and it is then accessible via the URL: http://localhost/


But will happen if you start to develop several sites simultaneously ?

You end up with a multitude of sub folders, and URLs to extension, for example:


Which will act as the site root url in the development phase.

The problem is that absolute and relative URLs do not work when you host your site (live) and sometimes you may be confronted to lengthy urls to access the site, etc. …) then this tutorial will be helpful.

The objective of the tutorial

We will create virtual host and use short addresses such as:


  • This tutorial was written for people working under Windows environment, and using XAMPP server. But you will probably have no difficulty to implement this method with other software.
  • Assuming you have installed XAMPP under C:xampp.
  • Assuming you have placed your current project under C:xampphtdocsMyProject.
  • You need a text editor, such as Notepad.

Set the host for windows

Open the file: C:WindowsSystem32driversetchosts
At the end of the file you should have something like this: localhost
::1 localhost

Add the following line to the end of it or below the above written lines

And save the file.

Note: If you can not edit the file, verify that it is not read-only. Under Vista or Windows 7, you may encounter more problems with the UAC. Make a copy of the file on your desktop, set the write permissions, make the change, then put the file in read-only, and overwrite the original file.

Configuring Apache

Find the httpd.conf file in the apache folder inside xampp.


Open the above file and add the following lines,

It is essential to properly put the two host definitions. 1st one to retain your original localhost definition, and the 2nd one for your desired host name.

Save the file.
Restart your Apache server.

PHP MySQL Interview Questions

I’ve been interviewed by many companies for PHP development positions, every company has a slightly different interview process, but there seems to be a lot of commonalities among them. I’ve outlined below the main areas that companies look for knowledge in, and some questions/answers you may get asked. At the end of the day you will not be able to entirely fake your way through a good interview, but I thought this would be a huge help for newer or mid level developers going into an interview. So given below are some PHP MySQL Interview Questions to help you out there.

Q1. What’s PHP ?

The PHP Hypertext Preprocessor is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications.

Q2. What’s a Session ?

A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests.

There is only one session object available to your PHP scripts at any time. Data saved to the session by a script can be retrieved by the same script or another script when requested from the same visitor.

Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.

Q3. What is a Cookie ?

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

Cookie is of two types 1) Persistent Cookie 2) Temporary Cookie

The setcookie() function is used to set a cookie.

setcookie(“user”, “Dipak”, time()+3600);

Here this cookie specifies that a cookie has been created which will be expired in next one hour holds the record that the current user is “Dipak”.

We can destroy the cookie by specifying expiry date less than the current time.

Q4. What is meant by PEAR in php ?

PEAR is short for “PHP Extension and Application Repository”. The purpose of PEAR is to provide:

  • A structured library of open-sourced code for PHP users
  • A system for code distribution and package maintenance
  • A standard style for code written in PHP

Q5. What is the difference between $message and $$message ?

$message is a simple variable whereas $$message is a reference variable. Here $message is a variable with a fixed name. $$message is a variable who’s name is stored in $message.
For example, if $message contains “var”, $$message is the same as $var.

Q6. What are the differences between require and include, include_once and require_once ?

The include() statement includes and evaluates the specified file. The documentation also applies to require(). The two functions are identical in every way except how they handle failure.  include() produces a Warning while require() results in a Fatal Error.

The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.

require_once() should be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinition, variable value reassignments, etc.

Q7. What are the differences between public, private, protected, static, transient, final and volatile ?

Public: Public declared items can be accessed everywhere.

Protected: Protected limits access to inherited and parent classes.

Private: Private limits visibility only to the class that defines the item.

Static: A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.

Final: Final keyword prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.

Transient: A transient variable is a variable that may not be serialized.

Volatile: A variable that might be concurrently modified by multiple threads should be declared volatile. Variables declared to be volatile will not be optimized by the compiler because their value can change at any time.

Q8. What is the difference between the functions unlink and unset ?

unlink() deletes the given file from the file system.
unset() makes a variable undefined.

Q9. What is meant by urlencode and urldecode ?

urlencode returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type.

urldecode decodes any %## encoded in the given string.

Q10. How can we submit a form without a submit button ?

Javascript submit() function is used to submit a form by using the form name.

By a OnClick callback function we can use “document.formname.submit();”.

We can do this by using ID also like, “document.getElementById(“FormID”).submit();”.

We can also use jQuery like, “$(“FormID”).submit();”.

Q11. What are the differences between GET and POST methods in form submitting ?

On the server side, the main difference between GET and POST is where the submitted is stored. The $_GET array stores data submitted by the GET method. The $_POST array stores data submitted by the POST method.

On the browser side, the difference is that data submitted by the GET method will be displayed in the browser’s address field. Data submitted by the POST method will not be displayed anywhere on the browser.

GET method is mostly used for submitting a small amount and less sensitive data. POST method is mostly used for submitting a large amount or sensitive data.

Q12. What are the different types of errors in PHP ?

Here are three basic types of runtime errors in PHP:

  1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script – for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all – although you can change this default behavior.
  2. Warnings: These are more serious errors – for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.
  3. Fatal errors: These are critical errors – for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP’s default behavior is to display them to the user when they take place.

Internally, these variations are represented by twelve different error types,

  • E_ERROR: A fatal error that causes script termination
  • E_WARNING: Run-time warning that does not cause script termination
  • E_PARSE: Compile time parse error.
  • E_NOTICE: Run time notice caused due to error in code
  • E_CORE_ERROR: Fatal errors that occur during PHP’s initial startup (installation)
  • E_CORE_WARNING: Warnings that occur during PHP’s initial startup
  • E_COMPILE_ERROR: Fatal compile-time errors indication problem with script.
  • E_USER_ERROR: User-generated error message.
  • E_USER_WARNING: User-generated warning message.
  • E_USER_NOTICE: User-generated notice message.
  • E_STRICT: Run-time notices.
  • E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error
  • E_ALL: Catches all errors and warnings

Q13. What is the difference between session and cookies ?

  • Session are temporary and Cookies are parmanent.
  • Session data is store on server while Cookies are store on user’s computer.
  • Cookies contents can be easily modify but to modify Session contents is very hard.
  • Cookies could be save for future reference but Session couldn’t when user close the browser Session data also lost.

Q14. What is the difference between array_merge and array_combine ?

array_merge merges the elements of one or more than one array such that the value of one array appended at the end of first array. If the arrays have same strings  key  then the later value overrides the previous value for that key.

array_combine creates a new array by using the key of one array as keys and using the value of other array as values.

Q15. What is difference between echo() and print() ?

echo() and print() function both are used to show the output on the visitors screen but in echo we can take one or more parameters.

print() has a return value of true or false whereas echo has a void return type.

echo() is slightly faster than print.

Q16. What is meant by MIME ?

WWW ability to recognize and handle files of different types is largely dependent on the use of the MIME (Multipurpose Internet Mail Extensions) standard. The standard provides for a system of registration of file types with information about the applications needed to process them. This information is incorporated into Web server and browser software, and enables the automatic recognition and display of registered file types.

Q17. What are the different types of MySQL Database Engines ?

Total 5 types of tables we can create

  3. MyISAM
  5. CSV
  8. InnoDB

Q18. What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row() ?

mysql_fetch_array() : Fetch a result row as an associative array, a numeric array, or both.

mysql_fetch_object() : Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows

mysql_fetch_row() : Fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Q19. What is difference between mysql_connect and mysql_pconnect ?

mysql_connect opens up a database connection every time a page is loaded. mysql_pconnect opens up a connection, and keeps it open across multiple requests.

mysql_pconnect uses less resources, because it does not need to establish a database connection every time a page is loaded.

Q20. What is JOIN in MySQL and explain different types of JOIN ?

JOIN is used to select relevant data between one or more tables.

There are three types of join in sql. that are as following:-
1) Inner join
1.1) equi join
1.2) natural join
2) Outer join
2.1)left join
2.2)right join
2.3) full join
3) Cross join

Q21. Why do we use ob_start() ?

ob_start() used to active the output buffering .When output buffering is on all output of the page sent at one time to the browser ,otherwise sometimes we face headers already sent type errors.

Q22. What is difference between single quotes and double quotes in php ?

When string is in single quotes php will not evaluate it . If there is a string with single quotes and if we place a variable in that it would not substitute its value in string where as double quotes support variable expansion. If we place variable in double quotes it would substitute its value in string.

Q23. What is a .htacces file ?

.htaccess is a configuration file running on Apache server.These .htaccess file used to change the functionality and features of apache web server .

  • .htaccess file used for url rewrite .
  • .htaccess file used to make the site password protected.
  • .htaccess file can restrict some ip addresses ,so that on restricted ip adresses site will not open.

Q24. What is difference between PRIMARY key and UNIQUE Key in sql ?

UNIQUE key can be a NULL value but PRIMARY key can not take NULL values.

A table can have multiple UNIQUE key but can only one PRIMARY key.

Q25. What is difference between TRUNCATE and DELETE in mysql ?

  1. DELETE is a DML(data manipulation lnguage) command where as truncate is a DDL(data definition language) command.
  2. Truncate is much faster than Delete.
  3. We can not roll back in truncate but in delete we can rollback.
  4. We can not use where clause in truncate but in delete we can use conditions using where clause.

Q26. What is use of header() function in php ? What the Limitation of header() ?

There are Number of use of header() function in php like below,

  • The header() function use to sends a raw HTTP header to a client.
  • We can use header() function for redirection of pages.
  • Use for refresh the page on given time interval automatically.
  • To send email header content like cc, bcc , reply to etc data and lot more.

In PHP, it is important to notice the limitation of header() function is that header() must be called before any actual output is send. Means must use header function before HTML or any echo statement.

Q27. What are the differences between procedure oriented languages and object oriented languages ?

There are lot of difference between procedure language and object oriented like below,

  1. Procedure language easy for new developer but complex to understand whole software as compare to object oriented model.
  2. In Procedure language it is difficult to use design pattern mvc, Singleton pattern etc but in OOP you we able to develop design pattern.
  3. IN OOP language we able to ree use code like Inheritance, polymorphism etc but this type of thing not available in procedure language on that our Fonda use COPY and PASTE.

A Guide To WordPress Custom Post Types: Create, Display & Meta Boxes

Custom Post Types are a new set of administrative options appearing along with the default post types such as PostsPagesAttachments etc. A Custom Post Type can store any type of information. It has a dedicated editor, media uploader and uses the existing WordPress table structure for ease in data management. The main advantage of creating custom post types using the WordPress API is that it equips itself well with existing themes and templates. Custom Post Types are also SEO friendly because of their nifty permalinks.

Why Use Custom Post Types?

Custom Post Types help us to keep different types of posts in different buckets. It separates our regular posts from others. Simple enough!

What Actually Are Custom Post Types?

Suppose you want your blog to have a separate section for Portfolio. By using Custom Post Types you can create a new type of item like Posts and Pages, which will contain a different set of data. It will have a new administration menu, dedicated editing pages, custom taxonomies and many more utilities required for full fledged publishing.

Let’s Create Custom Post Type “Portfolio” For Your New Portfolio Page

Register Custom Function :-

Add the below function to your theme’s function.php. The following line of code is used to execute the custom function named site_portfolio during the initialization phase every time a page is generated.

add_action( ‘init’, ‘site_portfolio’ );

Implement The Custom Function :-

The register_post_type function does most of the work for us. As soon as it is called it prepares the WordPress environment for a new custom post type including the different sections in the admin. This function takes two arguments: the first one is an unique name of the custom post type and the second one an array demonstrating the properties of the new custom post type. Here it’s another array containing the different labels, which indicates the text strings to be displayed in the different sections of the custom post type e.g. name displays the custom post type name in the dashboard, edit and view are displayed in Edit and View buttons respectively. I think the rest are pretty self explanatory.

In the next arguments:

  • 'public' => true determines the visibility of the custom post type both in the admin panel and front end.
  • 'menu_position' => 15 determines the menu position of the custom post type.
  • 'supports' => array( 'title', 'editor', 'comments', 'thumbnail' ) determines the features of the custom post type which is to be displayed.
  • 'taxonomies' => array( '' ) creates custom taxonomies. Here it’s not defined.
  • 'menu_icon' => get_bloginfo( 'template_url').'/images/portfolio.png'  displays the admin menu icon.
  • 'has_archive' => true enables archiving of the custom post type.

Icon for Custom Post Type :-

Save a 16×16 pixel icon image in your current plugin folder. This is required for the custom post type icon in the dashboard.

Creating Meta Box Fields for Custom Post Types

The meta box mechanism uses the help of the built in WordPress meta box system and helps to add fields required specifically for the custom post types, without requiring the default custom fields in the editor.

Registering the Custom Function :-

Open your theme’s function.php and add the following function. This registers a function to be called when the WordPress admin interface is visited.

add_action( ‘admin_init’, ‘my_admin_portfolio’ );

Implement The Custom Function For Meta Box :-

Here add_meta_box is the function used to add meta boxes to custom post types. Explanation of the given attributes:

  • portfolio_meta_box is the required HTML id attribute
  • Portfolio Details is the text visible in the heading of the meta box section
  • display_portfolio_meta_box is the callback which renders the contents of the meta box
  • portfolio is the name of the custom post type where the meta box will be displayed
  • normal defines the part of the page where the edit screen section should be shown
  • high defines the priority within the context where the boxes should show

Implementation of the display_portfolio_meta_box Function :-

This code renders the contents of the meta box. Here we have used an object variable that contains the information of each of the portfolio displayed in the editor. Using this object we have retrieved the post ID and used that to query the database to get the associated ‘Description’, ‘Type’ and ‘URL’ which in turn render the fields on the screen. When a new entry is added then the get_post_meta returns an empty string which results in displaying empty fields in the meta box.

Registering A Save Post Function :-

add_action( ‘save_post’, ‘add_portfolio_detail_fields’, 10, 2 );

This function is called when posts get saved in the database.

Implementation Of The add_portfolio_detail_fields Function :-

This function is executed when posts are saved or deleted from the admin panel. Here after checking for the type of received post data, if it is a Custom Post Type then it checks again to see if the meta box elements have been assigned values and then finally stores the values in those fields.

Creating a Custom Template Dedicated to Custom Post Types

  • archive-{post_type}.php
  • single-{post_type}.php
If your custom post type were ‘product’, WordPress would look for archive-product.php to display the archive of posts.
If your custom post type were ‘product’, WordPress would look for single-product.php to display the single or permalink of the post.

If these files are not available in your Theme’s directory WordPress will look for archive.php and single.php, respectively. If even these files are not present it will default to index.php.

Create PHP file named archive-portfolio.php and put the following code in it. It will display all the post having post type “portfolio”.

Now for displaying the detail of particular post create single-portfolio.php

Now create a page in admin named as “Portfolio” (same name as post_type) and save it. Now access your page by your domain name/portfolio.

Export MySQL To Excel Using PHP

Inserting data to your database and getting all the data when required is a much needed operation in websites maintenance or development. So making all these operations easy is really needy.

I am presenting you a PHP script to export mysql to excel sheet and download. Script is orginally written by Oliver Schwarz <>

Following are the script to call the class file and produce the output. Just download the php file and class file and follow the following steps,

1 : Create Download Link

<a href=”export.php”>Export To Excel</a>

2 : Include the .class file to “php-excel.php”

// load library
require ‘php-excel.class.php’;

3 : Include db file for database connection

// load your db file for databse connection
require ‘php-db-connect.php’;

4 : Set your column names for excel file

5 : Create loop to fetch data and write to excel file

6 : Create Excel File & Export MySQL to Excel

Its so easy and handy to use. Download

Live URL Of jQuery UI Themes

jQuery UI is a JavaScript library that provides abstractions for low-level interaction and animation, advanced effects and high-level, themeable widgets, built on top of the jQuery JavaScript library, that can be used to build interactive web applications.

You need to add the jQuery.ui.js file to enable your UI integration. And for the styles you need to include ui.css files. Switching with the themes is little difficult you you are downloading the files from the jQuery.ui site and including it to your html page.

A more easy way is there to play with all the themes provided by jQuery.ui without downloading all of them. Below are the live urls of the ui.css files for all the themes. Just put these urls in your scripting include and the ui theme for whole site will be changed and you can see the reflection at that instance.

Script to include your JS files to enable jQuery and jQuery UI Themes for your site,

<script type=”text/javascript” src=””></script>

<script type=”text/javascript” src=””></script>

Now add you css file for UI CSS. The url should be chnaged to change the UI theme,

<link rel=”stylesheet” type=”text/css” href=”DYNAMIC URL HERE” media=”screen” />

Now find below your desired theme and place that URL into the above code.



























All the css can be managed in the database also and you can have a nice UI theme chnager option for your site. I hope this post will help will somewhat.

Hide Files & Folders Using Command Prompt

You always wanted to hide your personal and confidential data from unknown or strangers eyes but using any software may charge you, here is a trick from which you can easily hide your content.

The most important thing is that, once hidden with this method, the files/folders cannot be viewed by any search options even if you click “Show All Hidden Files and Folders”.

You can now easily hide your files or folders through Command Prompt. It will be impossible for others to find the file or folder unless they know the file name or folder name. You can secure your documents easily by this method. Make sure you remember the file or folder name!

Hiding the most wanted files and folders is very important nowadays and it’s really a tedious job too. In order to make this tedious job an easy one, I’m going to deliver you this trick now.

Step 1 : Open Command Prompt

Hit Windows + R key on keyboard to enter into “RUN” mode.


Type “cmd” and hit Enter. 


Step 2 : Navigate To Desired Drive And Hide Item

In my case my folder “Private” is present inside E:


Now switch to command prompt and type “E:” and Hit Enter. You are now in E drive.


Here is your original command,

attrib +s +h Private

Otherwise you can directly enter the following command without switching to the drive E in following way,

attrib +s +h E:Private

step 3 : Unhide Your Item

In this trick you have to remember your folder or file name in order unhide, because you can not even find the item after you choose “Display Hidden Files And Folders”. Type the same code with (-) symbol.

attrib -s -h E:Private

Step 4 : Find Your Item In Emergency

Create a “” file in you drive and navigate to that folder to view all the hidden files applied through the command prompt,

I hope this trick will somewhat useful for you.