Tuesday, 30 August 2016

Implementing authentication with tokens for RESTful applications using yii2

REST is that its stateless protocol used for the api. This means that the server never keeps user state for this aspect we need to implement security for data exchanging between api's.We need to add authentication must be sent and verified at each time. There are many ways to secure your api to handle the authentication , the HTTP basic authentication and OAuth2 are default provided by the yii2.

Yii2 Authentication component are following:

HTTP Basic Auth: We need to send the access token as the username. This should only be used when an access token can be safely stored on the API consumer side. For example, the API consumer is a program running on a server.

Query parameter: In this we need to send access token as a query parameter in the API URL, e.g., https://yiiapp.local/users?access-token=xxxxxxxx. Because most Web servers will keep query parameters in server logs, this approach should be mainly used to serve JSONP requests which cannot use HTTP headers to send access tokens.

OAuth 2: The access token is obtained by the consumer from an authorization server and sent to the API server via HTTP Bearer Tokens, according to the OAuth2 protocol.

use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBasicAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;

public function behaviors()
    $behaviors = parent::behaviors();
    $behaviors['authenticator'] = [
        'class' => CompositeAuth::className(),
        'authMethods' => [
    return $behaviors;

Authentication in Yii2 : click here

I'm showing you how to use a custom authentication token for security of data exchange. You need to create a super controller (base) and it should be extended to all your child controller for the use of its common functions for resonse array and header genreate also you can write every api log into mongo db or other database using the base controller.

Now i'm using some algorthim for making the hash .I’m using the HMAC-SHA authentication implementation package for PHP. This package will allow you to create requests and hash them in your client code, and then authenticate the request on the API side.

1. You need to send the params input of user sending through the api like.

// Sending Params
$params = array('name' => 'Mark', 'email' => 'markg@gmail.com');

2. For Authenticate with the API, we have a key and a secret that only us and the API server know about. We can use this key and secret combination to create a Token. The api token will be shared to client who will be access the api.

Here i'm defining the apitoken key in the params common/config/params.php

return [

3. You have to make a hash with the sending query params and the api token key which you  have stored locally. Make a hash with using this algorithim.

$encodeData = json_encode($params);
$hash = hash_hmac('sha256', $encodeData, Yii::$app->params['ApiTokenKey']);

it will create a hash something like this:

4. Then send the hash in header with key X-API-TOKEN (you have to rename the key and change in your base controller for use).

5. When you send the request with the api header token the server file will use the same algorithim and  create a token in server end and verify both token will be same. If token will not same then return false with the error like:

  "status": true,
  "data": {
    "response": false,
    "message": "Invalid token credentials"

Please find the below code for using these algorthim in your end of controller files.

use yii\rest\Controller;
 * @author     SJ <imsonujangra@gmail.com>
 * @package    Base Controller API
 * @created    30-Aug-2016
 * @version    1.0
class ApiBaseController extends Controller

    public function response($code, $data = '')
        $response = array();
        $message = $this->getStatusCodeMessage($code);
        if (!empty($message)) {
            //$response = array("status" => false, "message" => $message, "data" => $data, "code" => $code);
            $response = array("status" => true, "data" => $data);

        echo json_encode($response);die;

    private function getStatusCodeMessage($status)
        $codes = Array(
            // Success 2xx
            200 => 'OK',
            201 => 'Created',
            202 => 'Accepted',
            203 => 'Non-Authoritative Information',
            204 => 'No Content',
            205 => 'Reset Content',
            206 => 'Partial Content',
            // Client Error 4xx
            400 => 'Bad Request',
            401 => 'Unauthorized',
            402 => 'Payment Required',
            403 => 'Forbidden',
            404 => 'Not Found',
            405 => 'Method Not Allowed',
            406 => 'Not Acceptable',
            407 => 'Proxy Authentication Required',
            408 => 'Request Timeout',
            409 => 'Conflict',
            410 => 'Gone',
            411 => 'Length Required',
            412 => 'Precondition Failed',
            413 => 'Request Entity Too Large',
            414 => 'Request-URI Too Long',
            415 => 'Unsupported Media Type',
            416 => 'Requested Range Not Satisfiable',
            417 => 'Expectation Failed',
            // Server Error 5xx
            500 => 'Internal Server Error',
            501 => 'Not Implemented',
            502 => 'Bad Gateway',
            503 => 'Service Unavailable',
            504 => 'Gateway Timeout',
            505 => 'HTTP Version Not Supported',
            509 => 'Bandwidth Limit Exceeded',
        return (isset($codes[$status])) ? $codes[$status] : '';

    private function setHeader($status)
        $status_header = 'HTTP/1.1 ' . $status . ' ' . $this->getStatusCodeMessage($status);
        $content_type = "application/json; charset=utf-8";
        header('Content-type: ' . $content_type);
        header('X-Powered-By: ' . "WantCode <WantCode.in>");

    public function authenticate($params)
        // If IS_AUTH is set in constant then required to check header 
        if (IS_AUTH) {
            $encodeData = json_encode($params);
            $msg = array('response' => false, "message" => "Invalid token credentials");
            $hash = hash_hmac('sha256', $encodeData, Yii::$app->params['ApiTokenKey']);
            if (!isset($_SERVER['HTTP_X_API_TOKEN'])) {
                $this->response(401, $msg);

            if ($_SERVER['HTTP_X_API_TOKEN'] != $hash) {
                $this->response(401, $msg);


If IS_AUTH is set in constant then required to check header authentication is used or not. so it should be true for the authentication is needed.

Now you can make your controller like SiteController.php in which a action like this:

class SiteController extends ApiBaseController
  public function actionAdd($domain)
        $params = Yii::$app->request->post();
 $this->authenticate($params); // base controller function for auth
        $data = array("data"=>array("message"=>"success"));
 $this->response(200, $data);

If you find any problem with these demo please don't hesitate to write a comment below .

Monday, 29 August 2016

How to perform database operations in yii2 using model.

In my previous post link i'll show how query builder we used for the sql statements. But here i'm explain how to used Model for sql operations.In this tutorial i'm using the active record class for the most common sql operation like select,update,delete etc.

Yii2 Active Record is the support for various new backends including NoSQL based ones. These backends include elasticsearch, redis, Sphinx search as well as mongodb. This is great news as we can switch backends without touching our code provided all our code uses Active Records for DB interaction.

Create a model class.


namespace frontend\models;

use Yii;

 * This is the model class for table "customers".
class Customer extends \yii\db\ActiveRecord
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 1;
     * @inheritdoc
    public static function tableName()
        return 'customers';


Fetching Data in Yii2 using Active Record:

// to retrieve all customers and order them by their ID:
$customers = Customer::find()
    ->where(['status' => Customer::STATUS_ACTIVE])

// to return a single customer whose ID is 1:
$customer = Customer::find()
    ->where(['id' => 1])

// to return the number of *active* customers:
$count = Customer::find()
    ->where(['status' => Customer::STATUS_ACTIVE])

// to index the result by customer IDs:
$customers = Customer::find()->indexBy('id')->all();
// $customers array is indexed by customer IDs

// to retrieve customers using a raw SQL statement:
$sql = 'SELECT * FROM customer';
$customers = Customer::findBySql($sql)->all();

// to return a single customer whose ID is 1:
$customer = Customer::findOne(1);

// to return an *active* customer whose ID is 1:
$customer = Customer::findOne([
    'id' => 1,
    'status' => Customer::STATUS_ACTIVE,

// to return customers whose ID is 1, 2 or 3:
$customers = Customer::findAll([1, 2, 3]);

// to return customers whose status is "deleted":
$customer = Customer::findAll([
    'status' => Customer::STATUS_DELETED,

How to perform database operations in yii2.

Build a yii\db\Query object to represent different parts (e.g. SELECT, FROM) of a SELECT SQL statement.Execute a query method (e.g. all()) of yii\db\Query to retrieve data from the database. This is used for directly using a query without any model relation.

$rows = (new \yii\db\Query())
    ->select(['id', 'email'])
    ->where(['last_name' => 'sharma'])

The Yii Query Builder provides an object-oriented way of writing SQL statements. It allows developers to use class methods and properties to specify individual parts of a SQL statement.

Creating a object of query builer like:

$connection = Yii::$app->db;

Raw SQL:

$connection->createCommand('update user set status = 1 where age > 30')->execute();

Raw SQL with placeholders (to prevent SQL injection):

$connection->createCommand('update user set status = :status where age > 30')->bindValue(':status','1')->execute();

update() method:

// update user set status = 1 where age > 30
$connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();

batchInsert() records:

$connection->createCommand()->batchInsert('tbl_user', ['name', 'status'], [['A', 1], ['B', 0], ['C', 1], ])->execute();

This is the direct method of accessing the query using query builer but apart from this you can create per table model for more superior way to manage your relation with the table and query are also simple. links for db query using model click here.

How to create user friendly clean seo url in yii2 with url manager.

Yii2 url router is a powerful and it helps to make a clean and pretty url.Yii2 URL router is quite powerful and does two main tasks: it resolves URLs into internal routes and creates URLs from these routes. If you want to hide index.php (http://yiiapp.local/index.php?r=site/test) from your url and make it clean like site/test.

'urlManager' => [
    'class' => 'yii\web\UrlManager',
    'enablePrettyUrl' => true,// Disable r= routes
    'showScriptName' => false,// Disable index.php

URL Rules Manage:

Clean url are help even better indexing for search engine. If that’s not enough consider the fact that you can hide the structure of your app by defining your own rules. ‘enableStrictParsing’ => true . it limits the access only configured rules. In the example given below http://yiiapp.local route will point to site/index, but the http://yiiapp.local/site/index will show a 404 page.For a securite reason you can always use enableStrictParsing .

'urlManager' => [
    'class' => 'yii\web\UrlManager',
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'enableStrictParsing' => true,
    'rules' => [
        '/' => 'site/index',
        'login' => 'site/login',
        'logout' => 'site/logout',

Custom URL Rules for configured urls:
yii\web\UrlRule is the URL rule class of yii2. Each and every url will be considered as pattern and accessed by this pattern rules. Here are some examples.

'components' => [
 'urlManager' => [    
  'showScriptName' => false, // Disable index.php
  'enablePrettyUrl' => true, // Disable r= routes
  'enableStrictParsing' => true,
  'rules' => array(
   'categorypage/<controller:\w+>/<action:\w+>' => '<controller>/<action>',
   '<controller:\w+>/<id:\d+>' => '<controller>/view',
   '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
   '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
   //Rules with Server Names
   'http://yii2app.local/login' => 'admin/user/login',
   'http://yii2app.local/login' => 'site/login',
   'http://<country:\w+>.domain.com/profile' => 'user/view',
   '<controller:\w+>/<id:\d+>-<slug:[A-Za-z0-9 -_.]+>' => '<controller>/view',

First Url: http://yiiapp.local/categorypage/add

In your controller action page like

public function actionAdd()

Second Url rule: http://yiiapp.local/mycategory/categorypage/page-one

Third Url rule: http://yiiapp.local/categorypage/index-one

For slug value url:

//URL Suffixes add like .html, .php
'components' => [
 'urlManager' => [
  'enablePrettyUrl' => true,
  'showScriptName' => false,
  'enableStrictParsing' => true,
  'suffix' => '.html',
  'rules' => [
   // ...


Every URL will be process by URL pattern rules. Some time we need to break a rule and override the rule like.

 // ...other url rules...   
 'suffix' => '.html',
 'rules' => array(
   'pattern' => 'site/test',
   'route' => 'site/contact',
   'suffix' => '.json',
   'pattern' => 'site/api',
   'route' => 'site/about',
   'suffix' => '.json',
   'pattern' => 'site/category',
   'route' => 'site/category',
   'suffix' => '/', //this will check site/category/ also
   '<controller:\w+>/<id:\d+>' => '<controller>/view',   
   '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',   
   '<controller:\w+>/<action:\w+>' => '<controller>/<action>',

Named Parameters Urls:

    'posts/<year:\d{4}>/<category>' => 'post/index',
    'posts' => 'post/index',
    'post/<id:\d+>' => 'post/view',

Sunday, 28 August 2016

Top ide for php developers

There are many IDE available for PHP But There are too many factors one look in a PHP editor and that’s why it become a tough decision for many of the developers. Development is a process where without tools the process can become more cumbersome and time-consuming.With the help of the IDE editor, we can easily configure the environment according to our need gain productivity from the IDE. Some other factors are also depend on choosing a best ide.


Featured looking for a perfect IDE's.

FTP Support: Means you can directory upload your files on server.

Workflow : The Workflow tools can enhance the overall idea of increasing productivity.With the workflow you can check your work in verison controlling tools like git,svn etc.

Language Support : Your IDE's should be supported to different language like PHP, Python, Javascript so you can easily work with native language also without changing IDE's.

Highlighting Code: Programmers love to see the higlight code which is easy to find bugs.

UI Factor: ui is good its matter for some people not everyone.

Plugins Support: Your IDE's should be supported to multiple pugins.

5 Top PHP IDE for Developers: 

1. PhpStorm : As one of the most commendable IDEs for HTML, PHP and Javascript. PhpStorm is the famous PHP IDE used by the programmers. It is fast and downright. The IDE supports lots of features like Code Completion, PHP refactoring, Code Rearranger, Intelligent Code Editor and more. The downside PhpStorm is that it is not available in free ya it's not a opensource so you can use it for 30days trial after that you need to purchase a licence for this. It supports PHP frameworks and its very easy to shift one framework to another with the ease and its having composer feature to add dependencies.Popular operating systems supported by PHPStorm include Windows, Linux and Mac OS X.

Features of PhpStorm:
Language Feature for support multiple language.
Code Compilation.
Code Formatting.
Framework Support.

2. NetBeans: NetBeans IDE is a modular developer tool for a wide range of application development technologies. The IDE includes an multi-language editor, Debugger and Profiler, as well as tools for versioning control and developer collaboration.It is feature rich, free and supports multiple languages, including English, Japanese, Russian, Brazilian Portuguese, and Simplified Chinese. It has been downloaded more than 18 million times and it is the biggest community of developers.Its support all PHP frameworks like Zend, Doctrine, Smarty and Symfony2, support for Laravel via laravel-ide-helper and support for other frameworks like Yii, CakePHP, FuelPHP and Wordpress CMS.

Features of NetBeans:
Follow Web Standards
Supports all PHP frameworks such as Zend, Symfony.
Supports Version Control.
PHP Unit for testing.
Supports Debugger.

3. Sublime Text 3: Sublime Text 3 is one of our favorites and a competing candidate for the most powerful text editors of all times. It is lightweight, feature rich and is supported on Windows. It is an amazing tool and it is a clean, functional, and fast code editor. Not only does it have incredible built in features ,also  it has support for plugins, snippets.

Features of Sublime Text:
Command Palette for easy navigation
Split Editing for seprate into two sections.
Distraction free mode for maximum concentration
Supports multiple selections.
Instant Project Switch.

4. Zend Studio 12 : It is one of the leading PHP development IDE that supports development and testing environment. It offers tons of features and creates the right environment for creating API and other kinds of PHP project.Debugging is very easy and powerful in Zend Studio 12. It is also a paid available for trail for some days.

Features of ZendStudio 12
create Android, iOS projects
Angular.js Supports
Can be used to create mobile application over PHP application.
REST services Supports.

5. Eclipse PDT: PDT means PHP Development Tools . It is another open source option that is also opensource technology. Eclipse has a huge community of developers working of plugins, required to empower eclipse with new features that other top class IDE like Storms PHP, NetBeans and Zend studio has to offers.

Features of Eclipse PDT:
Syntax highlighting.
Code formatter.
Code templates.
Code navigation.

Syntax validation.

Git repository with Bitbucket Cloud

As our new Bitbucket space station administrator, you need to be organized. When you make files for your space station, you’ll want to keep them in one place and shareable with teammates, no matter where they are in the universe.

Steps :

1. Create an account with bitbucket.

2. Create a Git repository : Initially, the repository you create in Bitbucket is going to be empty without any code in it.That‘s okay because you will start adding some files to it soon.This Bitbucket repository will be the central repository for your files, you can manage your repository public or private use.

Steps for create your repository.

click Repositories > Create repository button at the top of the page.

Then fill the detail repository name and description etc.I'm creating a test repo. Then after creating the repository.

3. Set up your local directory.

mkdir /path/to/your/project
cd /path/to/your/project
git init
git remote add origin git@bitbucket.org:xyz/test.git

4. Create your first file, commit, and push

echo "First commit" >> contributors.txt
git add contributors.txt
git commit -m 'Initial commit with contributors'
git push -u origin master

This will create a repo on your machine and push it over the bitbucket using git@bitbucket.org:xyz/test.git remote address.

5. Already have a Git repository on your computer? Let's push it up to Bitbucket.

cd /path/to/my/repo
git remote add origin git@bitbucket.org:xyz/test.git
git push -u origin --all # pushes up the repo and its refs for the first time
git push origin --tags # pushes up any tags

Now everything is setup on remote repo. Now you can modify your files and work with remote changes.

Learn git basics

GIT is a version controlled system which you can use to maintain code for your project. Its allows a team of people to work together, all using the same files. And it helps the team cope with the confusion that tends to happen when multiple people are editing the same files.It is a distributed source control system its simpler, faster, and easier to use than traditional "centralized" source control systems.

The Benefits of Using git for your local machine :

  • Working offline with the git.
  • Fast to Work With git : Most of the Git operations are fast, mainly because they are performed on your local repository copy.
  • Repositories Are Smaller.
  • Moving or Adding files : Also if you want to add only certain files with some extension with Git you can use wildcards. For example to add only .html files you can run.

git add '*.html'

Ignore Certain Files ex .gitignore
  • Branches for new work developement : Sometimes you need to work on new experimental features without interfering with the main code of your project.
  • Check the Status of Your Changes. (file change are shown in git status modified)
  • Stash Branches : If you are working on a branch of your project but you do not want to commit the changes, you can save the current status of that branch to return to it in the future. You can switch your work to another branch and insert the stashed modification in it. 
  • Cherry Pick Changes from Branches: Git allows to pick one commit from some branch and apply it into the current branch. This operation is helpful for testing purposes. Imagine you want to test some temporary modification or pick some commits done in other branches.
  • Debugging with Git find version : If you have an issue in your code and you want to know when it was introduced and what it is, with the git bisect command you could go back to every commit till you will find the bad one one which the issue was introduced.
1. Installation of git in ubuntu.

Linux – Simply open up a new terminal and install git via your distribution’s package manager. For Ubuntu the command is: 

sudo apt-get install git

 For window machine we recommend git for windows as it offers both a GUI client and a BASH comand line emulator.

After installing git configure the name and email .

git config --global user.name "My Name"
git config --global user.email myEmail@example.com

2. Creating a new repository.

git stores its files and history directly as a folder in your project. To set up a new repository we need to run the git init command in terminal.It

will enable the git in your local machine.

git init

Create a folder on your Desktop called git_example, open a new terminal and enter the following:

cd Desktop/git_example/
git init

The command line should respond with something along the lines of:
Initialized empty Git repository in /home/user/Desktop/git_example/.git/

This means that our repo has been successfully created but is still empty. Now create a simple text file called index.html and save it in the git_example folder.

3. Checking the file modified status using.

git status

It shows you is everything up to date, what’s new, what’s changed. Now it will show you index.html is new created file.

4. Staging : Git has the concept of a “staging area”. You can think of this like a blank canvas, which holds the changes which you would like to commit.git add command, and finally commit everything (create a snapshot) with git commit.

In our case we have only one file so let’s add that:

git add index.html

If we want to add everything in the directory, we can use:

git add -A

5. Commiting – A commit represents the state of our repository at a given point in time. It’s like a snapshot, which we can go back to and see how thing were when we took it.

git commit -m "Initial commit for index.html"

The -m "Initial commit for index.html" part is a custom user-written description that summarizes the changes done in that commit.

7 Beautiful Libraries must be used for php.

PHP is probably the most popular scripting language on the web. The PHP community on GitHub is also one of the biggest and most active, with new awesome projects coming out constantly.80% of the top 10 million websites use PHP. PHP is particularly popular for freelance work, since many small businesses or non-technical people would want to use PHP cms like wordpress and shopping cart or other content management systems.There are so many git contributor for php here i'll found some usefull library for everyone person must be used.

1. Monolog : It's sends your logs to files, sockets, inboxes, databases and various web services. See the complete list of handlers below. Special handlers allow you to build advanced logging strategies.This libaray is integrated with many frameworks as well like laravel , symfony, slim etc.

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));

// add records to the log

2. PHPExcel: It's an OpenXML - Read, Write and Create spreadsheet documents in PHP - Spreadsheet engine.

include 'PHPExcel/IOFactory.php';

$inputFileName = './sampleData/example1.xls';

echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory';
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);

$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);

3. Guzzle : It is one of the best HTTP clients out there. It can handle almost any HTTP task that you throw at it: synchronous and asynchronous requests, HTTP cookies, streaming of large uploads and downloads.

$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
    'auth' => ['user', 'pass']
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'

// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
    echo 'I completed! ' . $response->getBody();

4. Twig : Templating engine with a very clean “mustache” syntax that makes markup shorter and easier to write. Twig offers everything you would expect from a modern templating library: variable escaping, loops, if else blocks, as well as a secure sandbox mode for verifying template code.

// Template HTML

<p>Welcome {{ name }}!</p>

// Rendering

require_once '/path/to/lib/Twig/Autoloader.php';

$loader = new Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array(
    'cache' => '/path/to/compilation_cache',

echo $twig->render('index.html', array('name' => 'George'));

5. PHPMailer : Nothing will be complete without emailer so this api will help you for sending emailer.This project is backed by a huge community and is implemented in popular systems such as WordPress and Drupal, making it the safest choice for sending emails in PHP. It has SMTP support, can do HTML-based emails, and much more.

require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->setFrom('from@example.com', 'Mailer');


$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';

6. Ratchet : A PHP 5.3 library for asynchronously serving WebSockets. Build up your application through simple interfaces and re-use your application without changing any of its code just by combining different components.

class MyChat implements MessageComponentInterface {
    protected $clients;

    public function __construct() {
        $this->clients = new \SplObjectStorage;

    public function onOpen(ConnectionInterface $conn) {

    public function onMessage(ConnectionInterface $from, $msg) {
        foreach ($this->clients as $client) {
            if ($from != $client) {

// Run the server application through the WebSocket protocol on port 8080
$app = new Ratchet\App('localhost', 8080);
$app->route('/chat', new MyChat);

7. Alice : It's allows you to create a ton of fixtures/fake data for use while developing or testing your project. It gives you a few essential tools to make it very easy to generate complex data with constraints in a readable and easy to edit way, so that everyone on your team can tweak the fixtures if needed.

// Template in person.yml file
        firstName: '<firstName()>'
        lastName: '<lastName()>'
        birthDate: '<date()>'
        email: '<email()>'

// Load dummy data into an object
$person = \Nelmio\Alice\Fixtures::load('/person.yml', $objectManager);

How to upgrade and install PHP 7 on ubuntu?

PHP 7, which was released on December 3, 2015, promises substantial speed improvements over previous versions of the language, along with new features like scalar type hinting.There have been a whole host of improvements made to PHP but we won’t delve too deep into changes. This is how to update to the latest release for those of you running a Ubuntu Linux system.

1. We need to do is add the ppa to our system, update the software sources and install our new version of PHP. 

sudo add-apt-repository ppa:ondrej/php
sudo apt-get update

sudo apt-get install php7.0-cli php7.0-common libapache2-mod-php7.0 php7.0 php7.0-mysql php7.0-fpm

Other packages which might be useful include:

sudo apt-get install php-mcrypt php7.0-soap php7.0-mbstring php7.0-intl php7.0-xml php7.0-curl php7.0-gd

Now you can check the php version using.

php -v

Result will like this.

PHP 7.0.9-1+deb.sury.org~xenial+1 (cli) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
    with Zend OPcache v7.0.9-1+deb.sury.org~xenial+1, Copyright (c) 1999-2016, by Zend Technologies
    with Xdebug v2.4.0, Copyright (c) 2002-2016, by Derick Rethans

2. Upgrading PHP-FPM with Nginx:

Install the PHP-FPM package.

sudo apt-get install php7.0-fpm

You'll be prompted to continue. Press Enter to complete the installation.

3. Install the mysql be sure for the PHP mysql bindings.

sudo apt-get install php7.0-mysql

Note: If you have made substantial modifications to any configuration files in /etc/php5/, those files are still in place, and can be referenced. Configuration files for PHP 7.0 now live in /etc/php/7.0.

4. Open the default configuration of nginx.

sudo nano /etc/nginx/sites-enabled/default

In the file fastcgi_pass unix:/var/run/php5-fpm.sock; changes to unix:/var/run/php/php7.0-fpm.sock

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /var/www/html;
    index index.php index.html index.htm;

    server_name server_domain_name_or_IP;

    location / {
        try_files $uri $uri/ =404;

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;

Save and exit the file and restart the nginx server.

sudo service nginx restart

Now check the your document root /usr/share/nginx/html or /var/www/html it may change according to your server configuration.

sudo nano /var/www/html/info.php


5. Now see the action on browser.

Saturday, 27 August 2016

How to create a virtual host in apache server in ubuntu ?

Apache is most widely used server. It is developed and maintain by Apache software. It is an open source and available free to use. It runs on 67% of all webserver in all over the world.According to a Netcraft (www.netcraft.com) Web server survey 60% of all Web sites on the Internet are using Apache (62% including Apache derivatives), making Apache more widely used than all other Web servers combined.

Steps to install the apache2 server.

1. First you need to reindex the update of ubuntu using update command.

sudo apt-get update
sudo apt-get install apache2

2. You need to have a directory which is working something like http://localhost/project/public_html project is your directory which is located in /var/www/html/project/public_html

sudo mkdir -p /var/www/project/public_html

3. You need to grant the permission for the directory.

sudo chown -R $USER:$USER /var/www/html/project/public_html

The $USER variable will take the value of the user you are currently logged in as when you press "ENTER". we need to check also the read directory permission.

sudo chmod -R 755 /var/www/html

4. Make out a simple index.html page in the project/public_html directory.

sudo nano /var/www/project/public_html/index.html

Paste the code below  for html page.

    <title>Welcome to Sample Project</title>
    <h1>Success!  The project.local virtual host is working!</h1>

5. Create a new virtual host file for the project.Apache has a default configuration under the file 000-default.conf . so just copy that file into new file projectlocal.conf.

sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/projectlocal.conf

Then open file in your favourite editor which you like most.

sudo gedit /etc/apache2/sites-available/projectlocal.conf

<VirtualHost *:80>
    ServerAdmin admin@example.com
    ServerName project.local
    ServerAlias project.local
    DocumentRoot /var/www/html/project/public_html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

6. Enable the virtual host.

sudo a2ensite projectlocal.conf

When you are finished, you need to restart Apache to make these changes take effect:

sudo service apache2 restart

7. Final step make host file entry.

sudo nano /etc/hosts

Make a new entry of line like..   project.local

8. Open your browser and type http://project.local and show the result.

Install Django Framework in Ubuntu.

Python is a programming language developer by Guido van Rossum in 1990s.Django is a free and open source web application framework, written in Python. Its initial release was in 2005.Django will help you create a web application and rely on the framework to do a good deal of the heavy lifting.

Benefits of using Python and Django: 

  • Python has a clean syntax that resembles English.
  • object-oriented file handling.
  • multiple inheritance suppport.
  • clear, concise, and orthogonal syntax.
  • ‘del’ statement for all data types.
  • Python is stronger in areas like data manipulation, analytics, system administration, and scientific programming.
  • support for all major GUI frameworks.

Installation ways:
There are many approches to use django. It's depends upon your need and developement environment which you are using.

Install through pip in a Virtualenv: It is a flexible way to create a sepreate virtual env for the python django.This tool allows you to create virtual environments where you can install any python packages without affecting the rest of the system.


1. Before anything starting refresh you local package index before anything new installation.

sudo apt-get update

2. Install the pip (pip is a package management system used to install and manage software packages written in Python).

sudo apt-get install python-pip
sudo apt-get install python3-pip

(Note: for python2 use simple python for 3 use python3)

3. Next you have to install the virtualenv.

sudo pip3 install virtualenv

(Note: for python2 version use only pip for python3 use pip3 always)

4. Now, start a new project in your directory location, you can create a virtual environment for it. Start by creating and moving into a new project directory:

mkdir ~/pythonproject
cd ~/project

5. create a virtual environment within the project by typing:

virtualenv pythonenv

Now we should call our virtual environment and it should be activate by typing.

source pythonenv/bin/activate

Your console should change to that you are now in your virtual environment.


6. Now you can install the django for the project.

pip3 install django

Verify the django version.

django-admin --version

To leave the environment type: deactivate

7. Creating a Sample Project: Now you have django install in your directory then you can use django admin command to create a project.

django-admin startproject projectname
cd projectname

This will create a directory called projectname. If you are in project directory that you create with virtual environment command.you can place the script into the current directory by adding extra . (dot).

django-admin startproject projectname .

For python database (this uses SQLite by default).

python manage.py migrate

If you used the migrate command above, you need to create the administrative user manually.

python manage.py createsuperuser

To start a django server.

python manage.py runserver

Visit the action server_ip:8000 for admin server_ip:8000/admin.

How to install Yii2 in ubuntu.

There are two templates available for yii2 while installing. Choose according to your need if you need a simple application without backend module than basic will be good enough . But for whole functionality advanced application will be used.

Basic Application Template – a basic frontend application template.
Advanced Application Template – consisting of a frontend, a backend, console resources, common (shared code), and support for environments.

Yii2 Requirements:
PHP >= 5.4
Some of packages installed :- curl, openssl, mcrypt etc.

Before running the composer command . first we need to install lates update and upgrade of your machine server.

sudo apt-get update
sudo apt-get upgrade

Assuming that PHP , apache , mysql are already installed. If not installed than install the LAMP stack.

Installing Composer:
While running the composer token will be needed for processing. Then create GitHub personal API token.

# installing composer
curl -sS https://getcomposer.org/installer | php
# move composer globally
sudo mv composer.phar /usr/local/bin/composer
# check composer working

Download the repo
https://github.com/yiisoft/yii2-app-advanced/archive/master.zip  unzip it.

Run these commands to install dependency globally.

composer global require "fxp/composer-asset-plugin:~1.1.1"
composer create-project --prefer-dist yiisoft/yii2-app-advanced yii-application

The first command installs the composer asset plugin which allows managing bower and npm package dependencies through Composer. You only need to run this command once for all. The second command installs the advanced application in a directory named yii-application. You can choose a different directory name if you want.

1. Open a console terminal, execute the init command and select dev as environment.
php init

2. Create a new database and adjust the components['db'] configuration in common/config/main-local.php accordingly.

3. Open Console and run the migration command. ./yii migrate

4. Final step for /path/to/yii-application/frontend/web/ and using the URL http://frontend.local/

5. for apache set sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/yiiapp.conf.

sudo gedit /etc/apache2/sites-available/yiiapp.conf

<VirtualHost *:80>
    ServerAdmin admin@admin.com
    ServerName frontend.local
    ServerAlias frontend.local
    DocumentRoot /var/www/html/yiiapp/frontend/web
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined


6. Enabled the virtual host:
sudo a2ensite yiiapp.conf

7. Restart your apache server.
sudo service apache2 restart

8. Final make a host entry
sudo nano /etc/hosts   frontend.local

Now test your application at http://frontend.local. You can see a offical installation steps here link here.

Friday, 26 August 2016

How to serve your domain to your blogger address.

We are using blogger for blogging stuff ideas etc. We can publish our blog on Blogger with blogspot hosting like company.blogspot.com. But i want to host it on my custom domain like www.company.com. You can change it anytime and it won't you cause your any data.

First thing you need to purchase a domain.
There are many companies which offering the domain like godaddy.com , namecheap.com. After purchasing a domain you have a your ip address and a name.

Follow these steps.

1. Log in into google blogger account.

2. Click on the left menu setting tab and click on basic tab.

3. Check the publishing section and click +3rd party url for your blog.

4. You need to add domain with www as prefix. 

5. Once you have added the domain name with www. you will see an error saying 'We have not been able to verify your authority to this domain. Error 12. It will display a name label host for CNAME records.

6. Setting up CNAME record on your blog.

7. Login to your Godady account dashboard & click on manage domains.

8. Click on Manage Zones under DNS tab on header.

9. Then DNS Management page will open add your purchased domain name and click further.

10. The Records are shown. Click on Add record and select CNAME record & add both the record one by one from your blogspot setting given.

11. The last step where you just need to add 4 I.P. Address into your A record. The process is going to the be the same as above, all you need to do is add A record instead of CNAME. These given 4 ip added one by one.

12. Back to the 3rd step and tru again to add your custom domain. If you see an error again the wait for few hours and try again.

If you find any problem during the steps please comment here.

Thursday, 25 August 2016

why should we use framework php ?

A framework is a structure thats gives you a complete standard to solve your typical problems. like you are building a website with the login functionality than the session management will be done with the framework.For a beginners framework will offer a simplicity as well stability so it may be a good idea to use PHP frameworks. It will help reduce the bad coding and speed up the build process. Some people say that the Framework is a used by weak programmers those don't understand how to write a clean and stable code. It is a big debate question whether we used framework or not . But core langauge knowledge is important for starting into a framework.

The big advantages of using a frameworks are:

You don't need to build the whole code again like common query , session etc.

The frameworks code are contributed by a huge community so it is very safe to work with a stable framework.

If you build from a scratch than fewer security leaks are remain.

Model View Controller or MVC as it is popularly called is a software design pattern.Separation of presentation and logic aids in maintainability clean code is easy, understandable code.

Enforcing of good coding standards.

PHP has many input and output filtering functions which can add extra security layer to protect your website against certain attacks.

More Features like:

  • Form Validation are very easy with framework on server as well as client side.
  • Database Abstraction layer for database query.
  • Input/Output filtering.
  • Session And Cookie handling.
  • Pagination logic etc and attribute labaling.
  • The debug panel accelerates debugging by displaying all the information the developer.
  • Routing rule are pretty simple with the framework.
  • Output esacping for security reasons.
  • Command line interface for cron jobs and data migrations.

List of Popular PHP Frameworks:
  • Laravel
  • Yii
  • Zend Framwork
  • Symfony
  • CakePHP
  • CodeIgniter
  • Phalcon

Wednesday, 24 August 2016

What is PHP ?

PHP is a server side scripting language which is embedded in html pages. It was originally created by Rasmus Lerdorf. Rasmus gives a name called Personal Home Page and now it is called PHP (Hypertext Preprocessor language). It is support the all databases like Microsoft SQL Server , MYSQL , PostgreSQL , MongoDB etc.

The usual "Hello" code example for PHP is:

 echo "Hello World!\n";  

Why Php is so popular:

PHP is very easy curve to learn. no other language is as easy for a beginner to start.Java/Ruby/Python/C++ all require know OOPS and framework knowledge to start.

Installation on any server is easy.

Php is free and opensource technology so anyone can offord a opensource.

The famous and most popular cms are built with PHP like wordpress, drupal,joomla.

Huge list of Extensions and Add-Ons are available.

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts