Upload File Using cPanel API

cPanel is a web hosting control panel which is using for various aspects of website and server administration with a nice graphical interface. cPanel also has well-documented APIs to manage all kinds cPanel activities through API. Here I have shared a code snipped to uploading files using cPanel API. (Fileman::upload_files)

Parsing XML With Multiple Namespaces Using PHP

Yesterday, I had a very ugly XML data which had to parse. It has multiple namespaces and namespaces are irrelevant with DOM – I just wasn’t getting the nodeValue from the Element. It was parsing partially not all nodeValues due to namespaces are irrelevant with DOM. Then I applied little tricks onto it through XML children options. And I thought I need to share this code so other developers can save his time to get out this annoying issue.

Remove Default Search Box and Add Custom Box in DataTable

DataTable displaying a default search box while initializing it. So by default DataTable has a search box. But sometimes you might have to remove that default search box and add a custom search box. And place that somewhere in the page. This article will help you to do that.

$('#example').DataTable();

See the above snippet, If your DataTable initializing it like that, then default search box will display. You might think, I can just use “bFilter: false” option to remove that search box. Yes you can! but the problem is if you do that, then DataTable will disable/turn off the search functionality. But you have to only remove the search box not search functionality.

In this case, you can use "dom: 't'" option. This will keep the default functionality of DataTable and just remove the search box, pagination (just hide it). It will just show the table elements.

Here I have shared a code snippet, you can get the idea to accomplish it.

$(document).ready(function() {
  var users = $('#users').DataTable({
    "dom": "t"
  });

  $('#customSearchBox').keyup(function() {
    users.search($(this).val()).draw();
  })
});

See the full jsFiddle

Install Elasticsearch in Ubuntu 16.04

Elasticsearch is a distributed, real-time, full-text search engine. Elasticsearch developer by JAVA (based on Lucene). It has an HTTP web interface and schema-free JSON documents. In this article, I will describe how to install and then configure elasticsearch in ubuntu 16.04. Let’s see

Before you install elasticsearch, please ensure java is installed on your machine. If not then install java first before doing anything.

Install Elasticsearch in Ubuntu 16.04
Install Elasticsearch in Ubuntu 16.04

Installing Java 8

 First Add the Java PPA to apt package database.

sudo add-apt-repository -y ppa:webupd8team/java

Then run update commands to update your apt package database.

sudo apt-get update
Then install Java 8 and verify it is installed, run following command.

sudo apt-get -y install oracle-java8-installer
java -version
After successfully install Java, now you can install  Elasticsearch on your machine.

Installing and Configuring Elasticsearch

You can download elasticsearch from their official website elastic.co. It would be always good to download deb (Debian) version for the ubuntu, cause it has everything integrated to successfully run elasticsearch. You can also download it through the command line:

sudo wget https://download.elastic.co/elasticsearch/elasticsearch/elasticsearch-1.7.2.deb
Then install this as usual ubuntu way with the dpkg command:

sudo dpkg -i elasticsearch-1.7.2.deb

After execution this command your installation will be completed, now you have to configure elasticsearch. By default all configuration files of elasticsearch stored into the /etc/elasticsearch directory. Here you can get two files elasticsearch.yml and logging.yml. To configure the elasticsearch you have to open elasticsearch.yml file in your text editor.

sudo nano /etc/elasticsearch/elasticsearch.yml

Now find the line node.name and cluster.name in this file and uncomment it (remove # before them) and change the value of these two.

Find the line, network.bind_host uncomment it by removing the # character at the beginning of the line, and change the value to 0.0.0.0 so it looks like this:

network.bind_host: 0.0.0.0

After all done, elasticsearch will be installed on your computer, now just run this command to start elasticsearch.

sudo service elasticsearch start

For testing elasticsearch output. just type http://localhost:9200/ in your browser and see the possible response.

{
  "status" : 200,
  "name" : "sohel-rana-pc",
  "cluster_name" : "sohel-rana-elasticsearch",
  "version" : {
    "number" : "1.7.2",
    "build_hash" : "e43676b1385b8125d647f593f7202acbd816e8ec",
    "build_timestamp" : "2015-09-14T09:49:53Z",
    "build_snapshot" : false,
    "lucene_version" : "4.10.4"
  },
  "tagline" : "You Know, for Search"
}

Internationalization & Localization Application with CakePHP 3

CakePHP has one of the coolest features to make application Internationalization & Localization. It’s really easy to translate your application or website into multiple languages with CakePHP 3.  Let’s see it.

First of all, create a directory Locale inside PROJECT_ROOT/src

Create a subdirectory of each language (which language you want to translate your application) inside PROJECT_ROOT/src/Locale/. Subdirectory name can be anything (ex. english, french, etc), but prefer ISO code of the language (ex. en_US, fr_FR, bn_BN etc). So follow this tutorial and make your subdirectory name en_USfr_FR, and bn_BN

Create default.po file inside all subdirectories (en_USfr_FR, and bn_BN). And copy the following code in the respective file.

src/Locale/en_US/default.po

msgid "message"
msgstr "Hello World"

 

src/Locale/fr_FR/default.po

msgid "message"
msgstr "Bonjour le monde"

 

src/Locale/bn_BN/default.po

msgid "message"
msgstr "ওহে বিশ্ব"

Here msgid key of which will use inside the template (view files) and msgstr is the values which will gonna translate.

So now you have three different languages (en_USfr_FR, and bn_BN). and one key (message) which can be translated into these three languages.

Now use <?php echo __(‘message’); ?> in your view (any ctp file of your application).

Then open PROJECT_ROOT/config/app.php file and find

 'defaultLocale' => env('APP_DEFAULT_LOCALE', 'fr_FR')

and replace with your language.

But if you want to translate language in runtime then you can use it

use Cake\I18n\I18n;

I18n::locale('fr_FR');

I hope this article will help you to translate your application in multiple language.

CakePHP 3 – DebugKit Toolbar Not Visible

Are you looking for the solution of DebugKit Toolbar not visible in CakePHP 3? These small tips will help you do that. Ensure you have pdo-sqlite installed & enabled on your machine. Cause debugKit by default uses a sqlite db. If not then follow this instruction.

At first install pdo-sqlite in your machine.

sudo apt-get install php7.0-sqlite

Then restart your server (apache server)

sudo service apache2 restart

Now that will help you to visible the DebugKit Toolbar

 

Concurrency Issues With PHP Session

Concurrent connection means how many request sending/calling at the same time. It influences the application performances rapidly. When your application can handle as much as concurrent connections your application will become more stable, high scalable and faster as well. But concurrency might be a problem when you deal with PHP Session. It is the biggest challenges to avoiding concurrency issue in PHP, especially in PHP Session.

Most of the modern web browser sent concurrent connections to a specific domain to between 4 or 6. That means if your application has a lot of static assets (JS, CSS, Images, Fonts, etc), then these will be queued until browser get the response from the server for its first set of a request (4/6 concurrent request).

Concurrency Issues With PHP Session

PROBLEM:

By default, PHP uses files to storing the Session data. PHP either create a new Session or retrieve existing Session on each request when called session_start() function. So in this case, if your user sending multiple concurrent requests to the server which involves with Session data. PHP Session will lock and block your application’s concurrent request for that particular client. And every request will be served as sequentially instead of processing them concurrently.

BEHIND THE SENCE:

For the new user, PHP sent the unique identifier number to users computer and create a new file with the same unique identifier name for handle the session for that particular user. Otherwise, PHP retrieves existing session for that user. See this article to know how does session works.

Now assume, a user sent 6 concurrent requests to server and 4 of them involved with session data. So what happened that case? PHP will take the first request and open the session file and lock it. And other 3 requests will be queued until session file will be released. So that means your application will be blocked. After your first request’s done, it will release the session file and the second request will take it. It’s will happen for rest of the request.

Now think every request taken 400-500 ms to execute, that means your last (4th) request completed after 1600 ms cause it waited 1200 ms to complete first 3 requests. So in this way PHP Session blocked the application.

However, this concurrent issue happened for the same user only. Request from a user cannot block another user’s request.

You will be able to understand how this thing can affect your application performance. To improve application performance every developer needs to avoid this issue.

PSR in PHP

I believe you already heard about the PSR in PHP language. Today I am trying to help you to understand the what is PSR, how and why should we use it.

PSR in PHP

PSR knock as ‘PHP Standards Recommendation’ which is some recommendations for all PHP programmer when they write their code they should follow some rules and regulation. With following that recommendations anyone can understand other programmers code. It’s working like an eco-system or uniform system where we all following these systems. Basically, there are five PSR: PSR-0, PSR-1, PSR-2, PSR-3, PSR-4. So let’s see about these five.

PSR IN PHP
PSR IN PHP

Before we move forward we should need to know the history of PSR in PHP language. Honestly, there are no uniform coding standards for writing code for PHP programmer. Some programmer has written their code by with their own naming convention and coding style. Someone was following some framework’s conventions such as PEAR or Zend Framework. So there was a huge problem to understand other programmer’s code. Cause they do not follow any uniform rules and regulation.

With that passing time, FIG (Framework Interoperability Group) intends to introduce a cross-section of the PHP ecosystem, not exclusively framework developers. The main focus of FIG create a dialogue between project representatives, and with this concept, they were searching a suitable and useful way to work together and everyone comes under one ecosystem of PHP and they introduce some PHP Standards Recommendations (PSR-0, PSR-1, PSR-2, PSR-3, PSR-4).

 

PSR-0:

PSR-0 refers to the ‘Autoloader Standard’. it comes with huge advantages to reusable the codes and loading the classes. Before the PSR-0 has come, we were working with PHP 5 magic function _autoload() which is automatically loading the class we required and gives us a flexible way to create the instance that class. But with  _autoload() you can able to provide only one autoloader function. Later PHP 5.12 introduced spl_autoload() which provides to register multiple autoloader function. Then PHP introduces the spl_autoload_register() function which gives us permission to create a series of the autoloading function. After PHP 5.3 PHP support true namespace and then the FIG (Framework Interoperability Group) written some guideline for the PSR-0. Below are the requirements for PSR-0 compliance:

  • A fully-qualified namespace and the classes must have the following conventions  <Vendor Name>(<Namespace>)*<ClassName>.
  • Each and Every namespace must have a top-level namespace (“Vendor Name”).
  • A namespace can have as many as sub-namespaces according to need.
  • Namespace separator converted into DIRECTORY_SEPARATOR.
  • Underscore in the class name converted into DIRECTORY_SEPARATOR.
  • Vendor names, namespaces, and class names might be of any combination of lowercase and uppercase.

These are some requirements for the PSR-0.

 

PSR-1:

PSR-1 refers to ‘Basic Coding Standard’ for PHP programmers. Actually, PSR-1 focus on the naming convention, file structure etc. With these rules, the code is understandable to all programmers who follow the PSR-1 Rules. Below are the requirements for PSR-0.

  • Only allow to write <?php and ?> (<? and <? are not allowed) tags for PHP.
  • Only allow using UTF-8
  • Force to use PSR-0
  • Class name must be in PascalCase/StudlyCaps (that means follow Capitalization Conventions while write class name )
  • Class constants/global variable must be defined in UPPER_CASE with underscore separators.
  • Method names must be defined in camelCase.

These are some requirements for the PSR-1.

 

.PSR-2:

PSR-2 refers to ‘Coding Style Guide’ . Actually PSR-2is the extended and expands of PSR-1’s ‘Basic Coding Standard’. The main goal of the this Standard is moving all PHP programmer to follow a uniform coding guideline

  • The programmer must  follow a coding style guideline (PSR-1).
  • Code must have 4 space for indenting, tabs are not allowed.
  • Code should have the length limit (120 characters are known as soft limit and above 120 characters knock as hard limit. The code length limit should be 80 characters or less)
  • There MUST be one empty line after the namespace declaration, and there MUST be one blank line after the block of use declarations
  • Opening braces for classes MUST go on the next line, and closing braces MUST go on the next line after the body.
  • Opening braces for methods MUST go on the next line, and closing braces MUST go on the next line after the body.
  • Visibility MUST be declared on all properties and methods; abstract and final MUST be declared before the visibility; static MUST be declared after the visibility.
  • Control structure keywords MUST have one space after them; method and function calls MUST NOT.
  • Opening braces for control structures MUST go on the same line, and closing braces MUST go on the next line after the body.
  • Opening parentheses for control structures MUST NOT have space after them, and closing parentheses for control structures MUST NOT have space before.

These are some requirements for the PSR-2.

 

PSR-3:

PSR-3 refers to ‘Shared Logger Interface’ for PHP programmers. Which is for taking/storing the application/system log reports. When an application is running  then sometimes error, notice, alert, can be happened, in this situation we need to track/save these actions, and PSR-3 describe us how should we save these actions.

PSR-3 incorporating with eight Syslog levels of(debug, info, notice, warning, error, critical, alert and emergency), These Syslog levels describe as a function and it’s accept two parameters such as ‘Message’ and ‘Context’. Generally ‘Message’ is a string regarding with logs level and Context is for store additional information.

Recently monolog implemented PSR-3 so you can use monolog for storing your application log.

 

PSR-4:

PSR-4 is the most recent added by FIG (Framework Interoperability Group). The PSR-4 is working together with PSR-0 where needed. PSR-4 is the replacement of PSR-0. The main goal of PSR-4 is to remove the remnants of PSR-0 and the pre-5.3 days completely and allow for a more concise folder structure. You can see the specifications of PSR-4 from here

 

Conclusion

The PHP-FIG does a great job of centralizing PHP standards. With this following these standards every PHP programmers will going forward with the same  concept. So every PHP programmer should follow these standards, so they can working together.

 

 

 

 

 

How to Create Custom Filter in Twig

Twig is the Fast, Secure, Flexible, and Powerful template engine of PHP. It has lot’s of great features for develope the front end. It’s has tons of built in filters, but sometimes we need to create our own custom filter and use them into Twig. With this article I am trying to describe you how to create custom filter in Twig.

I am showing an example so you can understand better. Go, where your Twig in loading paste this code.

Here, the custom filter name is ‘convert_object_to_array‘ Which is responsible for convert an object to array. Now you can call that filter in your twig file by {{ objectData | convert_object_to_array }}. Now you can type casting your object into array with this custom filter.

 

 

 

 

What is AngularJS and How to Start

What is AngularJS?

AngularJS is the web application development framework which provides a flexible way to build testable and maintainable front-end applications. Generally, AngularJS javascript MV framework which is developed by google for build dynamic web application. For more details click here.

How to Start?

It’s really easy to start AngularJS. Just need to download AngularJS JavaScript file, and add to your web page with a script tag: You can also add it from remote url (e.g. http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js).  Here is an example code, so you can see how it works.

Explanation of this Code:

Here I will use 3 types of directives of AngularJS  which are:

ng-app:  This directive will define the angular application, That means this ng-app directive is for initializing the Angular into the page.

ng-model: This directive binds/takes the value from HTML controls (input, select, text area) to application data.

ng-bind: This directive  display the application data to the HTML view.

You can see ng-app directive is declared into the body tag that means Angular  is initialized among whole web page.  and the ng-model directive is declared three times called (name, title, and comment) and which was binds by {{name}}, {{title}}, {{comment}}
{{name}} bind for ng-model="name",
{{title}} bind for ng-model="title",
{{comment}} bind for ng-model="comment"

Output

What is AngularJS and How to Start
What is AngularJS and How to Start

Hope you can learn the basic concept of AngularJS from this article. Thanks!!!