Friday, 30 September 2016

How to create Directives in AngularJs

AngularJS: Directives are the most important components of any AngularJS application.It can help you to manage your code elegantly. If you already use Angular for a while, you must be familiar with ng-model, ng-click, ng-repeat and ng-show. All these directives attach special behavior to DOM elements. For example, ng-repeat repeats a specific element and ng-show conditionally shows an element.

AngularJS Directives


AngularJS directives are extended HTML attributes with the prefix ng-.

ng-app : It is initializes an AngularJS application.

ng-init: It is initializes application data.

ng-model: It is binds the value of HTML controls (input, select, textarea) to application data.

<div ng-app="" ng-init="firstName='John'">

<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>

</div>

How to Specify Directive in HTML: In AngularJS you can create directive as an element, class names, attribute and even comment. In below example teach you how directive can be initialised in html. I use “want-code” as my directive name.

<want-code></want-code> 
<div want-code></div>
<div class="want-code"></div>
<!-- directive: want-code -->

You can also use the directive like this.We use dash delimited for attribute directive because it is good practise.

<div want:code></div>
<div want_code></div>
<div want-code></div>
<div x-want-code></div>

How to create custom Directive in AngularJS:

// yourscript.js
...
.directive('userProfile', function() {
  return {
    template: 'Name: {{ user.name }} <br /> Gender: {{ user.gender }}   <br /> Phone: {{ user.phone }}'
  };
});

We define the user model inside the controller below.

// yourscript.js
...
.controller('MainCtrl', ['$scope', function($scope) {
  $scope.user = {
    name: 'John',
    gender: 'Male',
    phone: '919999999999'
  };
}])
...

Basically, it will display a template that contains user information using Angular binding.For Html it will defined as.

<user-profile></user-profile>

You may notice that we use dash delimited instead of camel cased (userProfile) for directive name in HTML. It is because HTML is not case sensitive so it doesn’t recognize camel cased.


Thursday, 29 September 2016

Most interesting modules for Python 2016

Python is often compared to other interpreted languages such as Java, JavaScript, Perl, Tcl, or Smalltalk.Comparisons to C++, Common Lisp and Scheme can also be enlightening.Python has a relative small quantity of lines of code, which makes it less prone to issues, easier to debug, and more maintainable.It is used in a wide industries and for a long list of different usages from websites and web applications to systems administration and desktop apps. It is the ideal language for the beginners and its simple and straight-forward syntax also encourages good programming habits, especially through its focus on white space indentation, which contributes to the development of neat looking code.

Python Modules


In this article i'm going to show some useful python libraries and i won't give a brief introduction of these libarary because it would blow-up the boundaries and for this article also.

mypy : Mypy is an experimental optional static type checker for Python and its aims to combine the benefits of dynamic typing and static typing. It combines the expressive power and convenience of Python with a powerful type system and compile time type checking. Mypy type checks standard Python programs run them using any Python VM with basically no runtime overhead.

Python:

def fib(n):
    a, b = 0, 1
    while a < n:
        yield a
        a, b = b, a+b

statically typed Python:

def fib(n: int) -> Iterator[int]:
    a, b = 0, 1
    while a < n:
        yield a
        a, b = b, a+b

matplotlib : If you want to show some graph experiance to your user than Matplotlib for you.Matplotlib is a python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. matplotlib can be used in python scripts.

import matplotlib.pyplot as plt

author__ = 'GHajba'

x_axis = [x for x in range(-3,4)]
y_axis = [x * x for x in x_axis]

plt.plot(x_axis, y_axis)
plt.show()

Requests :  The most famous http library written by kenneth reitz. It’s a must have for every python developer.

r = requests.get('http://httpbin.org/get')
print(r.status_code)
print(r.headers['content-type'])
print(r.encoding)
print(r.json())

Scrapy : An open source and collaborative framework for extracting the data you need from websites.
In a fast, simple, yet extensible way.If you are intrested in webscraping then this is a must have library for you. After using this library you won’t use any other.

pip install scrapy
 cat > myspider.py <<EOF

import scrapy

class BlogSpider(scrapy.Spider):
    name = 'blogspider'
    start_urls = ['https://blog.scrapinghub.com']

    def parse(self, response):
        for title in response.css('h2.entry-title'):
            yield {'title': title.css('a ::text').extract_first()}

        next_page = response.css('div.prev-post > a ::attr(href)').extract_first()
        if next_page:
            yield scrapy.Request(response.urljoin(next_page), callback=self.parse)
EOF
 scrapy runspider myspider.py

wxPython : A gui toolkit for python. I have primarily used it in place of tkinter. You will really love it.

Pygame : Which developer does not like to play games and develop them ? This library will help you achieve your goal of 2d game development.

nose:  A testing framework for python. It is used by millions of python developers. It is a must have if you do test driven development.

Pyglet : A 3d animation and game creation engine. This is the engine in which the famous python port of minecraft was made.

PeeWee :  It is an ORM (ORM) framework which comes in handy if you have an application where you have to fill data from objects (from class representations) to a relational database and vice versa.

import peewee

__author__ = 'GHajba'

db = peewee.SqliteDatabase('my_app.db')

class Book(peewee.Model):
    author = peewee.CharField()
    title = peewee.TextField()

    class Meta:
        database = db


if __name__ == '__main__':
    db.connect()
    Book.create_table(True)
    book = Book(author='Gabor Laszlo Hajba', title='Python 3 in Anger')
    book.save()
    for book in Book.filter(author="Gabor Laszlo Hajba"):
        print(book.title)
    db.close()

db = peewee.SqliteDatabase('my_app.db') 

In above example we create database table fill with data and extract the content.

I hope you liked this article. share your views in the comments below. Stay tuned for the next post.

Sunday, 25 September 2016

Getting started with node.js

Node.js – is server-side JavaScript.Node.js is an open source Javascript runtime environment for easily building server-side and networking applications. The platform runs on Linux, OS X, FreeBSD, and Windows, and its applications are written in JavaScript. Node.js also provides a rich library of various JavaScript modules which simplifies the development of web applications using Node.js to a great extent.

Getting started with node.js


Features of Node.js:
  • Asynchronous and Event Driven.
  • Very Fast.
  • Single Threaded but Highly Scalable.
  • No Buffering.
So in this tutorial i will teach you how to say hello using nodeJS.

Installation:

Update your package using
sudo apt-get update

Then use apt-get to install the git package, which npm depends on:
sudo apt-get install git

cd ~
wget https://nodejs.org/dist/v4.2.3/node-v4.2.3-linux-x64.tar.gz

Now extract the tar archive you just downloaded into the node directory with these commands:
mkdir node
tar xvf node-v*.tar.?z --strip-components=1 -C ./node

If you want to delete the Node.js archive that you downloaded, since we no longer need it. Then
cd ~
rm -rf node-v*

For globle prefix configuation
mkdir node/etc
echo 'prefix=/usr/local' > node/etc/npmrc

Now we're ready to move the node and npm binaries to our installation location.
sudo mv node /opt/

For changing the permission of root user.
sudo chown -R root: /opt/node

Create a symlinks:
sudo ln -s /opt/node/bin/node /usr/local/bin/node
sudo ln -s /opt/node/bin/npm /usr/local/bin/npm

Verify the node is installed using command.
node -v

Create a new file inside our node folder and name it  server.js. Open this file in your favorite editor and add the below piece of code.
var http = require("http"),
port = 8000;  
var server = http.createServer(function(request,response){  
response.writeHeader(200, {"Content-Type": "text/plain"});  
response.write("Hello HTTP!");  
response.end();  
});
server.listen(port);  
console.log("Server Running on "+port+".\nLaunch http://localhost:"+port);

Yes, that’s it. This is our HTTP server, that will understand all the HTTP requests and can respond accordingly.

In this code we simply load module system and specify the port which we are using for the app.Creates a new Server and this function takes a callback. Remember everything in Node is Async!. The anonymous function takes in the request and response object. 

Now back to the console and run.
node server.js

Open a browser and navigate to http://localhost:8000/  and there you can see your message!

This is just a simple handshake with the nodeJS but we can do a lot more with nodeJS. In future i will share more post on nodeJS.


Saturday, 24 September 2016

Quick Start with AngularJS 2.0

AngularJS has become one of the most popular open source JavaScript frameworks in the world of web application development.The AngularJS you know and, hopefully, love will still be there with data-binding, extensible HTML, and a focus on testability.The new Angular version will be focused on the development of mobile apps and it is for desktop as well, but mobile is the hard bit that we will get right first.Various new modules are added and remove from the angularJS resulting for better performance.

AngularJS 2.0


Get a Copy Of angularJS 2 project using GIT.

git clone https://github.com/angular/quickstart.git firstapp

This will clone the quick start project to firstapp folder.


  • Your created firstapp project will contain the libraries.
  • Pre-built ES5 version of Angular 2 alpha-11
  • Pre-built ES5 version of rtts-assert alpha-6
  • The es6-shim, which includes Traceur, ES6 Module Loader, System, Zone, and Traceur options for meta-data annotations.
WorkFlow of angularJS 2 directory.

.
├── angular2
│   └── src
│       ├── change_detection
│       │   ├── parser
│       │   └── pipes
│       ├── core
│       │   ├── annotations
│       │   ├── compiler
│       │   │   ├── pipeline
│       │   │   ├── shadow_dom_emulation
│       │   │   └── xhr
│       │   ├── dom
│       │   ├── events
│       │   ├── life_cycle
│       │   └── zone
│       ├── di
│       ├── directives
│       ├── dom
│       ├── facade
│       ├── forms
│       ├── mock
│       ├── reflection
│       └── test_lib
├── dist
└── rtts_assert
└── src

At the root of the directory you have a Gulpfile that consist of simple build tasks to download Angular 2.0 and its dependencies using the ng2build.sh.You have to installed nodeJS and gulp should be installed .

npm install -g gulp

#For install all dependencies.
npm install

#Now to regenerate Angular and its dependencies, run
gulp

Before we go further, I would recommend having a knowledge of EcmaScript 6.This knowledge is quite essential as Angular 2.0 is written for ES6 and to support ES5.

Build your first App with angularJS.

This Angular tutorial create the project related files at the root of the directory.With so much going on at the root of the directory, I found it easy to maintain the files inside a folder named app.This situation is temporary till Angular 2.0 moves to a stable release.So, create a new folder named app at the root of the project. Create a file named index.html inside the app folder. And update it as below.

firstapp/app/index.html

<html>
<head>
<title>Angular 2 Hello World!</title>
<script src="/dist/es6-shim.js"></script>
</head>
<body>
<my-app></my-app>
<script>
// Rewrite the paths to load the files
System.paths = {
'angular2/*': '/angular2/*.js', // Angular
'rtts_assert/*': '/rtts_assert/*.js', // Runtime assertions
'app': 'app.es6' // The my-app component
};
// Kick off the application
System.import('app');
</script>
</body>
</html>

Load up the es6-shim.js from the dist folder to work with ES6 in current browsers.
We created a new component named my-app. We will talk about components soon.
ES6 comes with Modules and Module Loaders.
Load a file named app.es6 it will be creating next. This file will consist the definition for  <my-app></my-app>.

create a new file named app.es6. The es6 extension indicates that you are loading a file with EcmaScript 6 syntax.

Update app.es6 file as below:
firstapp/app/app.es6JavaScript

import {Component, Template, bootstrap} from 'angular2/angular2';
// Annotation section
@Component({
selector: 'my-app'
})
@Template({
inline: '<h1>Hello {{ name }}</h1>'
})
// Component controller
class MyAppComponent {
constructor() {
this.name = 'World!';
}
}
bootstrap(MyAppComponent);


I was overwhelmed as well as confused when I first saw the code. Learning Angular 2.0 is a challenge in itself and adding ES6 touch to that makes this a bit tricky.

The first line will import the components from angular2.The “@” is an annotation. Angular 2.0 uses a library called AtScript (@ script).AtScript simplifies the syntax of ES6 in its own way. Taking an example from the primer.

ES6:
import * as rtts from 'rtts';
class MyClass {
constructor(name, list) { }
}
MyClass.parameters = [
{is: rtts.string}, 
{is: Array}
];


AtScript:
class MyClass {
constructor(name:string, list:Array) {}
}

Angular does not force the users to use AtScript but it definitely looks like an advantage working with it.Angular 2 works with a concept of components.The Annotation Section – This consist of the meta data (component selector, template) for that component.The Component Controller Section – This is a ES6 Class, from which the template would be reading the properties that are interpolated ({{…}}) inside it.

Launch and test the App:
firstapp folder or you can use a node module named http-server to do the same. You can install the same using the below command.

npm install http-server -g

And then you can launch the static server by running
http-server

from inside the firstapp folder. And then navigate to  http://localhost:8080/app/ you should see Hello World.You can also checkout the angular resources page here, which has a few but helpful links on Angular 2.0.

Friday, 23 September 2016

AngularJS, Backbone.js or Ember.js

Choosing a right javascript framework is a difficult choice. There are so many factors to consider and so many options out there that selecting a framework can be overwhelming. You probably want a solid, stable and proven framework to build upon, but don't want to be limited by your choice.
All of these javascript frameworks are open source and comes under MIT license and try to solve the problem of creating Single Page Web Applications using the MVC design Pattern.So, here are a few pros and cons of each framework.

emberjs, backbone and angular


AngularJS : It was born in 2009 as a part of a larger commercial product, called GetAngular. Angularjs is very fast. It can do some amazing things like two-way bindings without having to learn much and its easy to learn for the begininers.

Features: 
  • Create custom DOM elements: e.g.<slider start=-5 end=5 />
  • Invents its own concepts sometimes: scopes, directives, transclusion
  • Some concern with performance over many DOM elements
  • “Views do the UI, Controllers work out the logic behind the UI, Services take care of communication with the backend and hold together pieces of common and related functionality, while Directives make it easy to create reusable components and extending HTML by defining new elements, attributes and behaviors.”
  • Two way binding.
Angular's Templating engine is simply HTML with binding expressions baked-in. Binding expressions are surrounded by double curly braces:

<ul> 
    <li ng-repeat="framework in frameworks" title="{{framework.description}}">               
                  {{framework.name}} 
    </li> 
</ul>

EmberJS: It's roots go way back to 2007. Starting its life as the SproutCore MVC framework, originally developed by SproutIt and later by Apple.I believe that learning Ember is easier than Angular but it requires a highest learning investment at the beginning to get basic things done.The Angular and Ember communities are pretty big as well. Also lots of tutorial and activity in StackOverflow and IRC, but not as much as Backbone.


Features: 
  • Performance focus
  • Two way binding
  • Very low boilerplate - I like
  • Templating engine / handlebars
  • Routing & data layer
  • Docs and API seems a tad more friendly than angular in general
  • Ember API was changing a lot but is now stable
  • Server rendering is a bit easier - pure JS
  • Litters the dom with placeholder script tags - technically this is invisible but a bit gross. But they’re fixing this with a new component called HTMLBars. UPDATE: This isn’t an issue anymore, changes merged in.
Ember currently uses the Handlebars template engine, which is an extension to the popular Mustache templating engine.

<ul> 
    {{#each frameworks}} 
        <li {{bind-attr title=description}}> 
            {{name}} 
        </li> 
    {{/each}} 
</ul>

Backbone.js is a lightweight MVC framework. Born in 2010, it quickly grew popular as a lean alternative to heavy, full-featured MVC frameworks such as ExtJS. This resulted in many services adopting it, including Pinterest, Flixster, AirBNB and others.

Features: 
  • Views manipulate DOM directly - kinda icky in my POV, makes code harder to test and allows things to get tangled
  • Light & fast
  • 3rd party templating, usually underscore
  • No two way binding
  • Unopinionated and barebones - sometimes a good thing but doesn’t provide structure, many competing plugins / frameworks to choose from
  • Probably will have to use with marionette at least.

<ul> 
    <% _.each(frameworks, function(framework) { %> 
        <li title="<%- framework.description %>"> 
            <%- framework.name %> 
        </li> 
    <% }); %> 
</ul>

Ember's holistic approach which embraces MVC structure will make a lot of sense for developers who have a MVC programming background in Python, Java, C# or any other OOPS language concepts.Angular's approach for extending HTML will make a lot of sense for people who are web developers by heart.Backbone embraces minimalism and It's is small, fast and easy to learn, and provides the minimum that you need to get going.

Wednesday, 21 September 2016

Pre- and Post-Dispatch Hooks in zend framework

Zend_Controller_Action specifies two methods that may be called to bookend a requested action, preDispatch() and postDispatch(). These can be useful in a variety of ways: verifying authentication and ACL‘s prior to running an action (by calling _forward() in preDispatch(), the action will be skipped), for instance, or placing generated content in a sitewide template (postDispatch()).
Use of init() vs. preDispatch().

Pre- and Post-Dispatch Hooks in zend framework


The init() method is primarily intended for extending the constructor. Typically, your constructor should simply set object state, and not perform much logic. This might include initializing resources used in the controller (such as models, configuration objects, etc.), or assigning values retrieved from the front controller, bootstrap, or a registry. 

The preDispatch() method can also be used to set object or environmental (e.g., view, action helper, etc.) state, but its primary purpose is to make decisions about whether or not the requested action should be dispatched. If not, you should then _forward() to another action, or throw an exception. 

or

Like method name itself tells you, this method is called before dispatching process takes place, so it is called before the action method. So we could use it to modify headers, or set different sitewide template. We can also modify current request and set different dispatch flag (skip current action processing).  For example: we check if the user  hasIdentity() to access some password protected site. If not, we redirect him back to the login page. So, more logic applied here than in init() method.

First preDispatch() is called for instances of Zend_Controller_Plugin_Abstract. Here you have the request and response objects, so you might filter the request or do some preparation using the information from the request.

init() of the Zend_Controller_Action is called next as part of the constructor. It’s there to help you initialize your controller, without having to override and repeat the signature of the constructor (Zend_Controller_Action::__contruct()).

The controller’s preDispatch() method is called here. You can call $request->setDispatched(false) to skip the current action – not sure if you can do that in init().

If you want something to be executed before all actions - put it in a plugin and use one of the hooks (besides preDispatch() there is routeStartup and others),
    if you want before every action in a controller - init or preDispatch(),
    if only for a single action - the action itself.
What happens between init() and preDispatch() function calls? 

Almost nothing - preDispatch() is executed, and if you haven't called $request->setDispatched(false), the action is executed.

Note: _forward() actually will not work correctly when executed from init(), which is a formalization of the intentions of the two methods.  

Change Default Port of XAMPP Apache Server

This problem comes many times when you install skype and other application to your system that conflict the port issue with xampp port i.e 80 . So this post is all about how to change default port 80 to another.

Change Default Port of XAMPP Apache Server



This error is show in your xampp console
8:12:37 PM  [Apache]     Problem detected!
8:12:37 PM  [Apache]     Port 80 in use by “Unable to open process” with PID 4!
8:12:37 PM  [Apache]     Apache WILL NOT start without the configured ports free!
8:12:37 PM  [Apache]     You need to uninstall/disable/reconfigure the blocking application
8:12:37 PM  [Apache]     or reconfigure Apache and the Control Panel to listen on a different port

Change Default Port 80,443 of XAMPP Apache Server.

1) First, you need to open the Apache “httpd.conf” file and configure it to use/listen on a new port no.

To open httpd.conf file, click the “Config” button next to Apache “Start” and “Admin” buttons. In the popup menu that opens, click and open httpd.conf

2) Within the httpd.conf file search for “listen”. You’ll find two rows with something like;
#Listen 12.34.56.78:80
Listen 80

Change the port no to a port no. of your choice (e.g. port 1234) like below
#Listen 12.34.56.78:1234
Listen 1234

3) Next, in the same httpd.conf file look for “ServerName localhost:” Set it to the new port no.
ServerName localhost:1234

4) Save and close the httpd.conf file.

5) Now click the Apache config button again and open the “httpd-ssl.conf” file.

6) In the httpd-ssl.conf file, look for “Listen” again. You may find:
Listen 443
Change it to listen on a new port no of your choice. Say like:
Listen 1443

7) In the same httpd-ssl.conf file find another line that says, “<VirtualHost _default_:443>”. Change this to your new port no. (like 1443)

8) Also in the same httpd-ssl.conf you can find another line defining the port no. For that look for “ServerName”. you might find something like:

ServerName http://www.example.com:443 or  ServerName localhost:433

Change this ServerName to your new port no.

9) Save and close the httpd-ssl.conf file.

10) Finally, there’s just one more place you should change the port no. For that, click and open the “Config” button of your XAMPP Control Panel. Then click the, “Service and Port Settings” button. Within it, click the “Apache” tab and enter and save the new port nos in the “main port” and “SSL port” boxes. Click save and close the config boxes.

That should do the trick. Now “Start” Apache and if everything goes well, your Apache server should start up.

You will also see the Apache Port/s no in the XAMPP control panel has change to the new port IDs you set.

The open http:localhost:1234

Install Nginx along with apache in ubuntu

NGINX is a very fast Webserver, its faster than Apache (under similar conditions) because it doesn't need to spawn new processes or threads for each request like Apache does.Hence it also has a low memory foot print.Nginx and Apache are alternative web server softwares. Web server softwares serve web pages in response to browser requests.

Install Nginx along with apache in ubuntu


Nginx has few dependencies that Ubuntu doesn't already take care of. Here's what you'll need:
  • The Gzip modules requires the zlib library.
  • The rewrite module requires the pcre library.
  • SSL support requires the openssl library.
With the Ubuntu platform, the only library from the list above that you'll need to install is the pcre library. To install this, follow these steps:

sudo apt-get install libpcre3-dev

Nginx can use PHP5 with the help of PHP-FPM (an alternative PHP FastCGI implementation with additional features, which is useful to busier sites). Here’s how to install PHP-FPM:

Install PHP-FPM using command:
sudo apt-get install php5-fpm

After installing all above things now Installing Nginx:
sudo apt-get install nginx

Starting and stopping the server
sudo service nginx start

Top stop the Nginx server, issue the following command:
sudo service nginx stop

Configure nginx:
sudo nano /etc/nginx/sites-available/default (This is default file of nginx)

server {
listen 8081 default_server; //default port is change now because in port 80 apache already running
listen [::]:8081 default_server ipv6only=on;

root /usr/share/nginx/html; //directory path of nginx files you can change it to /var/www/html
index index.php index.html index.htm;

location ~ \.php$ {
# fastcgi_split_path_info ^(.+\.php)(/.+)$;
# # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
#
# # With php5-cgi alone:
# fastcgi_pass 127.0.0.1:9000;
# With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}

Activate the virtual host.
sudo ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled/default

Make sure your Document Root is correct. Save and exit the file and activate that virtual host:
sudo a2ensite default

sudo service php5-fpm restart
sudo service nginx restart

Check Your nginx : http://localhost:8081/

How to minify css and js in Yii2

Minification is the process of removing unnecessary or redundant data without affecting how the resource is processed by the browser - e.g. code comments and formatting, removing unused code, using shorter variable and function names, and so also you can compress your css and js file into one minified resource so it took less time response in server.



yii2-assets-auto-compressPlease add the dependency in your composer file:

"skeeks/yii2-assets-auto-compress": "*"

In your main.php (frontend->config->main.php)


//App config
[
'bootstrap' => ['assetsAutoCompress'],
'components' =>
[
'assetsAutoCompress' =>
[
'class' => '\skeeks\yii2\assetsAuto\AssetsAutoCompressComponent',
'enabled' => true, // false if you don't want to minify the assets
'jsCompress' => true,
'cssFileCompile' => true,
'jsFileCompile' => true,
],
]
]

Now you can can your compile assets on page.

Tuesday, 13 September 2016

How to install laravel for PHP web application developement

Laravel is an open source PHP framework, designed for the faster development in PHP. I have used almost all framework like zend, yii2, codeiginiter and etc but laravel is one which i recommened to use for PHP developement. Laravel is built to be simple, easy to learn and supports rapid application development. Laravel comes with a new template engine called "Blade".The feature of using blade template is its allow you to write plain PHP in your template.

Laravel PHP



Some key features of laravel:
  • Restful routing is easy.
  • Composer – An amazing tool that lets you manage your application’s third-party packages easily.
  • Built-in unit testing with easy syntex.
  • A lightweight Blade Templating Engine.
  • A huge community catering to thousands of programming geeks and application developers.


System requirements to install laravel framework:
  • PHP >= 5.4
  • Mcrypt PHP Extension
  • OpenSSL PHP Extension
  • Mbstring PHP Extension
After all lamp configuration you need a composer to download laravel and dependency from remote.

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

Install Laravel via Laravel Installer : First, download the Laravel installer using Composer

composer global require "laravel/installer"

Once installed, the laravel new command will create a fresh Laravel installation in the directory you specify. For instance, laravel new blog will create a directory named blog containing a fresh Laravel installation with all of Laravel's dependencies already installed.

laravel new blog (This command will create a laravel project named blog)

Via Composer Create-Project:

composer create-project --prefer-dist laravel/laravel blog

chown -R www-data.www-data /var/www/blog
chmod -R 755 /var/www/blog
chmod -R 777 /var/www/blog/app/storage

Installing the dependency of laravel using:

# installing using composer
composer install

Now set the 32 bit long random number encryption key, which used by the Illuminate encrypter service.

#genreate a application key
php artisan key:generate

Now edit config/app.php configuration file and update above generated application key.Also set the cipher.

'key' => env('APP_KEY', 'k3HTNu3A21Kt73loyr2Py9blU2J4XQ75'),
'cipher' => 'AES-256-CBC',

Create a virtual host for laravel blog(directory) and create virtual host like blog.laravel. If you don't how to create a virtual host in ubuntu please read the article here and after creating virtual host access your project in browser start building an awesome application with laravel.





Sunday, 11 September 2016

Ways to Secure PHP Web Applications and Prevent Attacks

PHP is one of the most popular programming languages for the web and it is easy language to learn, and many people without any sort of background in programming learn it as a way to add interactivity to their web sites.Here are a few of the more common security problems and how to avoid them.

PHP Security
PHP SECURITY

Cross Site Scripting (XSS): XSS attack means when hacker inject the javascript code in your html.

// GET data is sent through URL: http://yourwebsite.com/search.php?search=<script>alert('test')</script>
$search = $_GET['search'] ?? null;
echo 'Search results for '.$search;

// This can be solved with htmlspecialchars
$search = htmlspecialchars($search, ENT_QUOTES, 'UTF-8');
echo 'Search results for '.$search;

ENT_QUOTES is used to escape single and double quotes beside HTML entities.

SQL Injections : SQL injection happens when you interpolate some content into a SQL query string, and the result modifies the syntax of your query in ways you didn't intend.SQL injection attack can happen by injecting malicious SQL parts into your existing SQL statement.

$password = $_POST['password'];
$id = $_POST['id'];
$sql = "UPDATE Accounts SET PASSWORD = '$password' WHERE account_id = $id";

#Now suppose the attacker sets the POST request parameters to "password=xyzzy" and "id=account_id" resulting in the following SQL:

UPDATE Accounts SET PASSWORD = 'xyzzy' WHERE account_id = account_id

Although I expected $id to be an integer, the attacker chose a string that is the name of the column. Of course now the condition is true on every row, so the attacker has just set the password for every account. Now the attacker can log in to anyone's account -- including privileged users.

To prevent the application from the sql injection.

Filter Input: use a data type coercion like the intval() function. 
Escape Output: Escapes literal quote characters and any other characters that may be string boundaries(such as mysql_real_escape_string() in PHP).

Session Hijacking: Session hijacking occurs when a session token is sent to a client browser from the Web server following the successful authentication of a client logon.Session hijacking is an attack where attacker steals session ID of a user. 

Remote File Inclusion: Remote file inclusion attack (RFI) means that attacker can include custom scripts.

$page = $_GET['page'] ?? 'home'
require $page . '.php';


In the above code $_GET can be set to a remote file http://yourwebsite.tld/index.php?page=http://example.com/evilscript

You have to disable this in your configuration.
; Disable including remote files
allow_url_fopen = off
; Disable opening remote files for include(), require() and include_once() functions.
; If above allow_url_fopen is disabled, allow_url_include is also disabled.
allow_url_include = off

Error Reporting: Always turn off error reporting on your production environment. If error reporting is on then any error occur will show to users and attackers can get information based on errors.


; Disable displaying errors to screen
display_errors = off
; Enable writing errors to server logs
log_errors = on


//Remote Files: Disable the remote files.
; disabled opening remote files for fopen, fsockopen, file_get_contents and similar functions
allow_url_fopen =  0
; disabled including remote files for require, include ans similar functions
allow_url_include = 0

Session: PHP is by default configured to store session data on the server and a tracking cookie on client side (usually called PHPSESSID) with unique ID for the session.

; in most cases you'll want to enable cookies for storing session
session.use_cookies = 1
; disabled changing session id through PHPSESSID parameter (e.g foo.php?PHPSESSID=<session id>)
session.use_only_cookies = 1
session.use_trans_sid = 0
; rejects any session ID from user that doesn't match current one and creates new one
session.use_strict_mode = 0

If some attacker want to inject javascript code for stealing user current cookie .you can use HttpOnly to disallow.
session.cookie_httponly = 1

For your domains specific you can use .example.com or set this to the domain it should be applied.
session.cookie_domain = example.com

For HTTPS sites this accepts only cookies sent over HTTPS. If you’re still not using HTTPS, you should consider it.
session.cookie_secure = 1

Tuesday, 6 September 2016

Improve PHP Performance

In this lession i'm going to tell you some useful tips and techniques to improve and optimse your php code. These tips are basics and some techniques are already done in frameworks.

PHP Tips & Tricks


1. Ternary Operators : A ternary operator is a different way to layout a simple if else statement.We'll just use a simple check to see if a GET parameter is set and not empty, if it is we will default to the word Hello, otherwise use the value that was set as the GET parameter.

$name = (!empty($_GET['name'])? $_GET['name'] : 'Hello');

2. echo vs print : PHP sting functions to printing output into browser and we are often using print() and echo() function.Print() will return an integer value.so print() can used as part of expression which more complex.echo() is able to accept more than one parameters all at once and it doesn't have any return value.

<?php
print() 'string 1';
echo 'string 1';
// using some parameters
echo 'string 1', "string 2", '...';
?>
echo is faster than print 

3. Loop in PHP : Dont use the count function on loop statement ex. for($i = 0; $i < count($array); $i++) it's slow down the process because checking every time count on a loop.

<?php
$max = count($array);
for ($i = 0; $i < $max; $i++)
//is faster than
for ($i = 0; $i < count($array); $i++)
When checking the length of strings:
Use isset where possible in replace of strlen. (cite)
if (!isset($foo{5})) { echo "Foo is too short"; }
//is faster than
if (strlen($foo) < 5) { echo "Foo is too short"; }

4. Single Quotes vs Double Quotes: single quotes and doubles quotes are easy to use but using a right quotes for your need boost your application.

<?php
  echo 'hello world';
?>
<?php
  echo "hello world";
?>

5.Incrementing in PHP: 

Use pre-incrementing where possible as it is 10% faster.

++$i;
//is faster than
$i++;

Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.

6. true vs TRUE : This is because when looking for constants PHP does a hash lookup for name as is & since names are always stored lower cased, by using them you avoid 2 hash lookups. By using 1 and 0 instead of TRUE and FALSE, can be considerably faster.

7: Use isset() instead of strlen() function:


<?php
$str = "45e23";
if (!isset($str{5})) {
    echo 'String must be at least 5 characters<br />';
}
if (strlen($str) < 5){
    echo 'String must be at least 5 characters;
}
?>



isset() take little more time than strlen() because isset() is a language construct.

8. Omit the closing php tag:


<?php

echo "Hello";

//Now dont close this tag

This will save you lots of problem. Lets take an example :

A class file super_class.php
<?php
class super_class
{
    function super_function()
    {
        //super code
    }
}
?>


//super extra character after the closing tag

Now index.php

require_once('super_class.php');

//echo an image or pdf , or set the cookies or session data
And you will get Headers already send error.Because the super extra character has been echoed , and all headers went along with that. Now you start debugging. You may have to waste many hours to find the super extra space.

Hence make it a habit to omit the closing tag :

<?php
class super_class
{
    function super_function()
    {
        //super code
    }
}

//No closing tag
Works better.

9. Dont use require , include , require_once or include_once: Don't include script files on top , like class libraries , files for utility and helper functions etc like this.

require_once('lib/db.php');
require_once('lib/common.php');
 
require_once('helpers/some_library.php');

Best way to use it. Write up helper functions to include things more easily. Lets take an example :

function load_class($class_name)
{
    //path to the class file
    $path = ROOT . '/lib/' . $class_name . '.php');
    if(file_exists($path))
    {
        require_once( $path ); 
    }
}
 
load_class('db');
load_class('common');

Benfits of using load class:

It will search multiple directory same time.
Change the directory containing class files easily , without breaking the code anywhere.

10: Class Autoloading: We include a large number of files in our top header scripts. But what if we have a very large number of classes that we could potentially use within one or many sections of our code.So instead of including classes that might not get used, or we might remove later, we can employ class autoloading.autoload classes will notify or throw an error that we've not included the class file.PHP function spl_autoload_register() we used for the autoloading the class files.

function loadMyClass($class){
    echo 'We are loading class: ' . $class;
    include_once('classes/' . $class . '.inc.php');
    echo 'Class loaded.';
}

spl_autoload_register('loadMyClass');

The first parameter of the function is specified the class name.

spl_autoload_register(function ($class){
    echo 'We are loading class: ' . $class;
    include_once('classes/' . $class . '.inc.php');
    echo 'Class loaded.';
});


If you like the post please share and comment.

Sunday, 4 September 2016

Git 2.10 released new features!

Git 2.10 has arrived with many new features!

git 2.10

  • Progress reports for pushes
  • New color attributes.
  • Improvements to GPG signature verification.
Progress reports for pushes: Git 2.10 adds progress reports for these post-receive operations, to keep you entertained and to make sure the network knows we're still going.

git 2.10


Signature verification improvements: GPG signed tags and commits have been a part of Git for a long time, but the workflows and tooling around them are still not that convenient to use. Along with some behind the scenes robustness improvements, it adds a new configuration option, log.showSignature, to verify signatures for every invocation of git log.

More color attributes: Git 2.10 comes with a few new options: its color code now understands italic and strikethrough attributes.

git 2.10 color attribute



For more information, check this out : click here

How to search with elasticsearch using Yii2

Elasticsearch is a type of Data ware house, where you have documents with many different attributes and non-predictable schemas. It will stored all the records in his document based object and you will be able to search them easily and quickly.It doesn't have tables and schema is not required in elasticsearch . It will stores data documents that consist of JSON strings inside an index.



If you need to setup elasticsearch in your machine please read this post How to install and use elastic search server in ubuntu .Now in this lession i will describe you how we used elasticsearch in yii2 .

The main features of elasticsearch are:
  • Distributed (data can be distributed to thousands of nodes).
  • Very powerful searches.
  • Easy to Scale ( can scale to thousands of nodes easily)
  • Real-time ( the data is available almost immediately after inserts)

When you save a document in Elasticsearch, you save it in an index. An index is like a database in relational database. An index is saved across multiple shards and shards are then stored in one or more servers which are called nodes, multiple nodes form a cluster.

{
    "id": 1,
    "name": "John",
    "author_name": "John"
    "publisher_name": "Admin",
    "created_at": "2016-09-03",
    "updated_at": "2016-09-03",
    "status": "1"
}

Installing elasticsearch using composer in Yii2:

Add following line in your composer.json file.


"yiisoft/yii2-elasticsearch": "~2.0.0"

After adding the line, run the following command in the terminal.

composer update

After succesfully installing the elasticsearch configure the host address of elasticsearch.
Application Folder -> config -> main.php

'elasticsearch' => [
    'class' => 'yii\elasticsearch\Connection',
    'nodes' => [
    ['http_address' => '127.0.0.1:9200'],
    //configure more hosts if you have a cluster
    ],
],

Using Elasticsearch in Yii2: You need to simple extend your model class with \yii\elasticsearch\ActiveRecord.The activerecord we are using for accessing elasticsearch database.Now create a several method for indexing and mapping of data.

<?php

namespace frontend\models;

use Yii;

/**
 * @author     SJ <imsonujangra@gmail.com>
 * @package    Users elastic search 
 * @created    03-Sept-2016
 * @version    1.0
 */
Class Users extends \yii\elasticsearch\ActiveRecord
{

    // Other class attributes and methods go here
    // ...
    public static function index()
    {
        return "sample";//index name
    }

    public static function type()
    {
        return "sample";//index type
    }

    public function attributes()
    {
        return [
            'name',
            'author_name',
            'publisher_name',
            'created_at',
            'updated_at',
            'status'
        ];
    }

    /**
     * @return array This model's mapping
     */
    public static function mapping()
    {
        return [
            static::type() => [
                'properties' => [
                    'name' => ['type' => 'string',"index" => "analyzed","store" => "yes"],
                    'author_name' => ['type' => 'string'],
                    'publisher_name' => ['type' => 'string'],
                    'created_at' => ['type' => 'date'],
                    'updated_at' => ['type' => 'date'],
                    'status' => ['type' => 'long'],
                ]
            ],
        ];
    }

    public static function setUpMapping()
    {
        $db = static::getDb();

        //in case you are not using elasticsearch ActiveRecord so current class extends database ActiveRecord yii/db/activeRecord
        // $db = yii\elasticsearch\ActiveRecord::getDb();

        $command = $db->createCommand();

        /*
         * you can delete the current mapping for fresh mapping but this not recommended and can be dangrous.
         */

        // $command->deleteMapping(static::index(), static::type());

        $command->setMapping(static::index(), static::type(), [
            static::type() => [
                //"_id" => ["path" => "id", "store" => "yes"],
                "properties" => [
                    'name' => ["type" => "string","index" => "analyzed","store" => "yes"],
                    'author_name' => ["type" => "string"],
                    'publisher_name' => ["type" => "string"],
                    'created_at' => ["type" => "date"],
                    'updated_at' => ["type" => "date"],
                    'status' => ["type" => "long"],
                ],
            ],
        ]);
    //echo "<pre>";print_r($command);die;
    }

    /**
     * Set (update) mappings for this model
     */
    public static function updateMapping()
    {
        $db = static::getDb();
        $command = $db->createCommand();
        $command->setMapping(static::index(), static::type(), static::mapping());
    }

    /**
     * Create this model's index
     */
    public static function createIndex()
    {
        $db = static::getDb();
        $command = $db->createCommand();


        $command->createIndex(static::index(), [
            //'settings' => [ /* ... */],
            'mappings' => static::mapping(),
            //'warmers' => [ /* ... */ ],
            //'aliases' => [ /* ... */ ],
            //'creation_date' => '...'
        ]);
    }

    /**
     * Delete this model's index
     */
    public static function deleteIndex()
    {
        $db = static::getDb();
        $command = $db->createCommand();
        $command->deleteIndex(static::index(), static::type());
    }
    
}

Create a controller and use the model class for users operation .Add use frontend\models\Users in your controller namespace and create a object on model class to use its static functions for index creation and update mapping etc.

Create an index :

$userObj = new Users();
$userObj::createIndex();

This command create an index mapping for the name given in your model class Users.

After successfully creating the index in your elasticsearch . you can check the index is created or not using to hit the address in your browser.

http://localhost:9200/sample/_search?pretty

Now the sample index are empty . Its time to add some document in index of elasticsearch.

$userObj = new Users();
$userObj->name   = "Dino";
$userObj->author_name = "Dino";
$userObj->publisher_name = "Admin";
$userObj->created_at = date('Y-m-d');
$userObj->updated_at = date('Y-m-d');
$userObj->status = 1;
$userObj->save();

please check the mapping function for model class in which data type of given fields are mentioned and also which field we need for index stored etc.This command will add a new data in elasticsearch. Add some more data to elasticsearch then check the records using

ttp://localhost:9200/sample/_search?pretty

You can also try to use hq and head plugin to see the document of index in graphical interface.I'm using head plugin and insert some test records like..

elasticsearch head plugin


Then how to search a record in elasticsearch using yii2. In mapping we add the stored to yes . it means we can perform the operations on it.

$userObj = new Users();
$result = $userObj::find()->query(["match" => ["name" => "Peter"]])->all();
echo "<pre>";print_r($result);die;

It will display all records match will the name peter in your index of elasticsearch.You can run the query like this also.

use yii\elasticsearch\Query;
 
$query = new Query();
$query->source('*');
$query->from(Users::index(), Users::type())->limit(10);
 
//execute the query
$command = $query->createCommand();
$rows = $command->search(); 

For the aggregation in query your can use like:

$query->addAggregation("status", "terms", array("field"=>"status" , "order" => ['_term' => "asc"]));
$query->addAggregation("author_name", "terms", array("field"=>"author_name",'size' => 25));

For elasticsearch Query and ActiveRecord you can follow the yii2 document here. If you find this post is intresting please like comment and share.



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