SSH Connection from local pc to Amazon(aws) EC2 ubuntu instance with new user and keys

In Amazon Elastic Cloud Compute(EC2), a key need to assign when creating an instance. ssh connection can be establish by using that key.

ssh -i your_private_key.pem username@hostname

If you have a ubuntu instance the username may be “ubuntu”

Now, we need to allow another user from another local machine to connect your remote server via ssh.

1. Generating key pairs for your local machine:
Open your terminal(Ctrl+Alt+t), in your local machine, write
ssh-keygen -t rsa

it will create two files id_rsa and in .ssh directory under your home directory, where id_rsa is your private key and is your public key.

2. Configure remote server

Create a new user on remote server:
adduser testuser

Login with newly created user:
sudo su testuser

Creating authorized_keys file:

cd $HOME
mkdir .ssh
chmod 700 .ssh
vi .ssh/authorized_keys

press i for insert mode, copy content and paste here. Press ESC, then :wq saving changes.

Changing file permissions and owner:

chmod 600 .ssh/authorized_keys
chown testuser:testuser .ssh
chown testuser:testuser .ssh/ authorized_keys

Now you can able to connect with your remote server from local machine without locating .pem file:
ssh testuser@hostname

WordPress Error handling with WP_Error class

WordPress have WP_Error class for checking WordPress errors and error messages since version 2.1.0. WordPress use object of WP_Error class for reporting error from several WP function. However, we can use this object in plugin or theme to handle error within WordPress. This class containing verious useful method for managing error.

Constructor of WP_Error allow three parameters: $code, $message and $data
Syntex is:

$error = new WP_Error( $code, $message, $data );

here, $code containing error code. it may be string or integer, $message containing error messagea and $data containing error data. however all paramater are optional.

Let we want to report new error, so we may use

$error = new WP_Error( 'not_found', 'Page Not Found', 'Page Data' );

Here, we consider not_found as error code, ‘Page Not Found’ as error message and ‘Page Data’ as error data

After creating error object we can check error by is_wp_error function.

if( is_wp_error($error) )
    echo $error->get_error_message();
//Output: Page Not Found

here, get_error_message function will get the first message available for the code. If no code is
given then the first code available will be used. If there are more then one error code in error object, then we may need to get error message by error code. In that case we may use”

echo $error->get_error_message( 'not_found' );

Here is example of using all method from WP_error class

//Creating instance of error class
$error = new WP_Error( 'not_found', 'Page Not Found', 'Page Data' );

//Add new error to object
$error->add( 'not_match', 'Field Not Match' );

//Return all error codes from object
$data = $error->get_error_codes();
print_r( $data );
//Output: Array ( [0] => not_found [1] => not_match )

//Return first error code
echo $error->get_error_code();
//Output: not_found

//Return all error message
$data = $error->get_error_messages();
print_r( $data );
//Output: Array ( [0] => Page Not Found [1] => Field Not Match )

//Return error message by error code
$data = $error->get_error_messages( 'not_match' );
print_r( $data );
//Output: Array ( [0] => Field Not Match )

//Return first error message if no code are given
echo $error->get_error_message();
//Output: Page Not Found

//Return first error message for given error code
echo $error->get_error_message( 'not_match' );
//Output: Field Not Match

//Return first error data
echo $error->get_error_data();
//Output: Page Data

//Return error data from error code.
echo $error->get_error_data( 'not_found' );
//Output: Page Data

//add error data to error code
//syntex: add_data( $data, $code );
$error->add_data( 'Some data', 'not_match' );
echo $error->get_error_data( 'not_match' );
//Output: Some data

//Check whether variable is a WordPress Error.
//return bool True, if WP_Error. False, if not WP_Error.
$data = is_wp_error( $error );
var_dump( $data );
//Output: bool(true)

WordPress Frontend AJAX Dropdown

AJAX is already built into the wordpress. all ajax request can be handle by admin-ajax.php
For frontend, wp_ajax_nopriv_ can used beside wp_ajax_

This is some sample code (plugin) to allow user to select sub category from parent category by ajax load.

Plugin Name: Frontend AJAX Dropdown
Plugin URI:
Description: WordPress Frontend AJAX Dropdown
Version: 0.1
Author: Khaled Hossain Saikat
Author URI:

//Add shortcode [ajax-dropdown] to any post or page

if (!class_exists('frontendAjaxDropdown')):
    class frontendAjaxDropdown{

        function __construct(){
            add_shortcode( 'ajax-dropdown', array(__CLASS__, 'init_shortocde') );   //Add shortcode function

            wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); // setting ajaxurl
            add_action( 'wp_ajax_get_subcat', array(__CLASS__, 'getSubCat') );  //Register ajax action
            add_action('wp_ajax_nopriv_get_subcat', array(__CLASS__, 'getSubCat')); ////Register ajax action for non loged in user

        function init_shortocde(){
            //Show parent dropdown for wordpress category
            wp_dropdown_categories('name=main_cat&selected=-1&hierarchical=1&depth=1&hide_empty=0&show_option_none=All Categories');

            <script type="text/javascript">
                    		type: "post",url: "<?php echo admin_url( 'admin-ajax.php' ); ?>", data: { action: 'get_subcat', cat_id: $("#main_cat option:selected").val() },
                    		beforeSend: function() {$("#loading").fadeIn('slow');},
                    		success: function(data){

            <div id="loading" style="display: none;">Loading...</div>
            <div id="sub_cat"></div>


        // AJAX action
        function getSubCat(){
            //Shows dropdown for selected parent


$frontendAjaxDropdown = new frontendAjaxDropdown;


PHPUnit test with Yii application

Unit tests are written to provide the developer with verification that the code is doing the right things.
this tests focus on the smallest units within a software application. In an object-oriented application, (such as a Yii web application) the smallest units are the public methods that make up the interfaces to classes. Unit tests should focus on one single class, and not require other classes or objects to run. Their purpose is to validate that a single unit of code is working as expected.

Basic conventions and steps for writing tests with PHPUnit:
1. The tests for a class Abc go into a class AbcTest.
2. AbcTest inherits (most of the time) from PHPUnit_Framework_TestCase.
3. The tests are public methods that are named test*.
4. Inside the test methods, assertion methods such as assertEquals() are used to assert that an actual value matches an expected value.

Writing Tests for PHPUnit in Yii:
A unit test in Yii is written as a PHP class that extends from the framework class, CTestCase. The conventions prescribe it be named AbcTest where Abc is replaced by the name of the class being tested. For example,
if we were to test MyClass, we would name the test class MyClassTest. This class is saved in a file called MyClassTest.php under the folder protected/tests/unit/.The test class primarily has a set of test methods named testXyz where Xyz is often the same as the method name the test is built for in the class being tested.Continuing with the MyClassTest example, if we were testing our Helloworld() method, we would name the corresponding test method in our MyClassTest class, testHelloworld().

For those testing, Create the new file, protected/tests/unit/MyClassTest.php and add to it the following code:

<!--?php class MyClassTest extends CTestCase { 	public function testHelloworld() 	{ 		$val=true; 		$this--->assertTrue($val);

Run phpunit tests in Command-Line:
The PHPUnit command-line test runner can be invoked through the phpunit command.
Now we can navigate to our tests folder and execute the command to run this test:
%cd /WebRoot/demo/protected/tests
%phpunit unit/MyClassTest.php

Test Result:
[saikat@folsom tests]$ phpunit unit/MyClassTest.php
PHPUnit 3.5.12 by Sebastian Bergmann.


Time: 0 seconds, Memory: 4.00Mb

OK (1 test, 1 assertion)

For each test run, the PHPUnit command-line tool prints one character to indicate progress:
.    Printed when the test succeeds.
F    Printed when an assertion fails while running the test method.
E    Printed when an error occurs while running the test method.
S    Printed when the test has been skipped.
I    Printed when the test is marked as being incomplete or not yet implemented.
PHPUnit distinguishes between failures and errors. A failure is a violated PHPUnit assertion such as a failing assertEquals() call. An error is an unexpected exception or a PHP error. Sometimes this distinction proves useful since errors tend to be easier to fix than failures. If we have a big list of problems, it is best to tackle the errors first and see if we have any failures left when they are all fixed.

More help on phpunit can be found by typing ‘phpunit –help’ on command line.

One of the most time-consuming parts of writing tests is writing the code to set the world up in a known state and then return it to its original state when the test is complete. This known state is called the fixture of the test.
PHPUnit supports sharing the setup code. Before a test method is run, a template method called setUp() is invoked. setUp() is where we create the objects against which we will test. Once the test method has finished running, whether it succeeded or failed, another template method called tearDown() is invoked. tearDown() is where we clean up the objects against which we tested.

Setting Fixture in Yii:
A test fixture is a system state or context in which tests are run. We want to run our tests a multiple number of times, and each time they run, we want to be able to have them return repeatable results. A fixture is intended to provide a well-known and fixed environment in which to run our tests. Typically, a fixture’s job is to ensure that all of the objects involved in the testing are consistently initialized to a particular state. One typical example of a fixture is the loading of a database table with a fixed and known set of data. Fixtures in yii are PHP files that return an array specifying the initial data configuration. They are typically named the same as the database table they represent, and are located under the protected/tests/fixtures/ folder.

Configuring the fixture manager:
was actually already done for us when we created the initial application. If we open up the application configuration file specific to testing, protected/config/test.php, we will see the following application component defined:
‘fixture’=>array( ‘class’=>’system.test.CDbFixtureManager’, ),
So the application has already been configured to use this fixture manager. we need to separate our development database from our testing database so that our testing will not continue to interfere with
our development.

<!--?php return CMap::mergeArray( 	require(dirname(__FILE__).’/main.php’), 	 	array( 		‘components’=-->array(

				‘connectionString’=>’DSN for test database’,
				‘connectionString’ =>
				‘emulatePrepare’ => true,
				‘username’ => ‘our_username’,
				‘password’ => ‘our_password’,
				‘charset’  => ‘utf8',

We still need to tell our unit tests to actually use this fixture we just created. We do this in the unit test file. In this case, we will need to add our fixture declaration to the top of our test file protected/tests/unit/EventsTest.php as such:
public $fixtures=array(‘events’=>’Events’);

DownloadPHPUnit Test Sample




Using jQuery with Yii

Yii is a high performance PHP framework, which has all sort of weapon to build up your efficient web application. Most popular javascript library jQuery are already  included with the core of this framework, so for using jquery no one need to included it.

For register jquery as core of your application just need to add one line code in main view file.

<?php Yii::app()->clientScript->registerCoreScript('jquery'); ?>

With yii default settings, this file can be found in ”protectedviewslayouts’ directory. Under this directory find main.php and put those code into HEAD section.

Normally we use jquery in a script tag like that:

	alert('hello world');

In Yii we can use jquery within our php code. like that:

		alert('hello world');

Here, ‘testscript’  parameter are nothing just a name of your script which need to be unique in a view file. POS_READY is identical to $(document).ready(). You can use POS_HEAD to put your script in head section. This way of using jquery will automatically prevent conflict of several javascript in your applicatio

Add FTP info to your wordpress site

Sometimes wardpress asking you for ftp details when you are going to add new plugins or themes or going to upgrade. In that case it also restrict you to edit your file or .htaccess file. This problem occur while your  wordpress don’t have sufficient or wrong FTP info for accessing your files in server. o

To overcome this problem, let your wordpress know about your FTP account by adding those lines in wp-config.php file.

define('FTP_HOST', '');
define('FTP_USER', 'FTP_Username');
define('FTP_PASS', 'FTP_password');
//*For using SSL Connection set this to true*
define('FTP_SSL', true);
After adding those line,  your wordpress won’t going to ask for your FTP account anymore.

PHP Script for downloading folder as zip file

I spent sometimes with searching some class for making zip file with php script, and finally got a class from

so i customized those file and make a single file for downloading all file  from a directory or sub-directory.  However, this script response slowly while directory contains huge amount of files or sub-directory

Download customized script:


Base class of this script collected from: