Tag Archives: php

How to make NetBeans 8 for PHP look more like Notepad++

Writing on the same subject here as the last 2 articles (line-spacing and python support) on NetBeans.

Little back-story, for the past 7 years I worked and I’m still working all my web-related projects in Notepad++. I’ve tried all the IDEs out there, didn’t liked any of them for reasons more or less logical (Yes, sometimes I listen my feelings/emotions when making choices, for example “I like this editor or not” :p )

Recently I decided to give another try at NetBeans (following my colleagues persistence 😀 ) and first thing I wanted to do was to make it look more like my notepad++. Especially when it comes to color highlight and syntax.

I found the same question being asked here. One of the answers gave a full solution to the case: a download offering all the color-configs for making the NetBeans IDE show PHP codes colored like Notepad++ does.

You can download it from the following link: Notepad++ Theme for NetBeans 6.7.x

1. Unzip file
2. From menu go Tools/Options then click on Import button in the shown dialogue browse the unzipped folder
3. From the shown tree check “Fonts & Colors” and click on OK button.
4. After restarting IDE again from menu goto Tools/Options select Fonts & Colors tab and from Profile combo box select “Notepad_plusplus”
have a nice time.

Since I have no idea if the download link will work forever (probably not :p) or if the original poster will take it down, etc, etc, I am uploading the source on my blog as well and provide it for download from the link below. Again, all the credits go to the original author and to the user who posted the solution on the askubuntu.com forum: Saeed Zarinfam (I don’t know if the author of the config files is the same person with the author of the post, whomever they are, many thanks!)

Download directly: Notepad_plusplus_Theme_for_NetBeans_6.7.x_(php5-html-css)

Basic PHP PDO Extension Usage & Syntax

PDO Extension defines a consistent interface for accessing databases in PHP.

What does that mean? Well, it means programmers can write PHP codes which can be easily ported from one database type to another; let’s say you write your codes for MS SQL but then suddenly the project takes a turn and you need to adapt your codes for MySQL … would be great to be able to make the transition easy, wouldn’t be?

Now, you can read all about it on the Official PHP Manual and also you can read tutorials about it, but I’m about to give you below a simple example of the basic PDO Syntax.

$db = new PDO(
	'mysql:host = localhost; dbname=someDbName; charset=utf8', 

	$res = $db->query('err');
catch(PDOException $ex){
	echo "error";

//other code examples:
$stmt = $db->query('select * from table');
$results = $stmt-?fetchAll(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();

//here's how to get the ID of the last inserted row
//when you're doing an insert before
$lastId = $db->lastInsertId();

//preparing queries
$stmt = $db->prepare("select * from table where id=:id and name=:name");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

Setup new Centos VPS with LAMP, Git and gitolite

Recently I had to install and maintain several Centos servers and I had to repeat the same setup instructions multiple times.

I thought it’d be nice to have the following list of to-do steps which needed to be repeated on every server install, especially so other employees could take on this job after me.

The scenario I had to work on required the setup of a new Centos 6 server with LAMP (php 5.5 at least) and configuring Git and gitolite for git user-managing access.

So the first thing was to install a Centos 6.5 minimal distribution and then all the work was done through Putty and heavy-usage of yum.

To avoid conflicts later-on because of repository packages, one of my colleagues recommended me to use yum-plugin-priorities. (thanks, Madalin 😉 )

Now, although this plugin is a bit controversial, we found that during our exploitation it was really helpful in preventing our servers to become a packages-mess in no-time. So I’m gonna go along and recommend it further. You should go however to the link and read the documentation for yum-plugin-priorities to see if it suits your needs and to learn how to proper configure it.

So here’s the list. It’s not something new or original content, it’s more of a compilation list to have all the info in one place. I have included links to the sites from where the info was used.

  1. Install yum-plugin-priorities (say yes if you’re asked about a key, it’s because you’re using the repo’s for the first time
    yum install yum-plugin-priorities
  1. install wget:
    yum install wget
  2. cd to user’s home:
    cd ~
  3. install remi repo:
    wget http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpmwget
    rpm -Uvh remi-release-6*.rpm epel-release-6*.rpm

    You can read more about the remi repo here.

  4. install webtatic repo:
    rpm -Uvh http://mirror.webtatic.com/yum/el6/latest.rpm

    You can read more about the webtatic repo here.

  5. Important! edit repo files located in /etc/yum.repos.d/ and enable the ones you want and add priority=N, according to yum-priorities plugin required settings (http://wiki.centos.org/PackageManagement/Yum/Priorities)
  6. update your system
    yum update
  7. install sort-of lamp, but don’t install php, since we need php 5.5 at least which we’ll get from the webtatic repo one step later:
    Install Apache and start it:

    yum install httpd
    service httpd start

    Install MySQL and start it:

    yum install mysql, mysql-server
    service mysql start

    Secure your fresh MySQL installation by running this script:


    You can read more about the default configuration for securing your mysql on this tutorial from digitalocean.com

  8. Install PHP 5.5 and the modules you want (we installed them all)
    yum install php55w  php55w-bcmath  php55w-cli  php55w-common  php55w-dba  php55w-devel  php55w-embedded  php55w-enchant  php55w-fpm  php55w-gd  php55w-imap  php55w-interbase  php55w-intl  php55w-ldap  php55w-mbstring  php55w-mcrypt  php55w-mssql  php55w-mysqlnd  php55w-odbc  php55w-opcache  php55w-pdo  php55w-pear.noarch  php55w-pecl-apcu  php55w-pecl-apcu-devel  php55w-pecl-memcache  php55w-pecl-xdebug  php55w-pgsql  php55w-process  php55w-pspell  php55w-recode  php55w-snmp  php55w-soap  php55w-tidy  php55w-xml  php55w-xmlrpc
  9. don’t forget to add chkconfig setting so the services would start automatically
    chkconfig --levels 235 httpd on
    chkconfig --levels 235 mysqld on
  10. Optionally, install nodejs, if you need it (we did)
    yum install nodejs
  11. Install the dev-tools
    yum groupinstall "Development tools"
  12. Install Git and create user/group
    yum install git
    useradd git
    usermod -u 600 git
    groupmod -g 600 git
    passwd git
  13. Install gitolite on the server by loging in as git user and cloning the gitolite repo
    git clone https://github.com/sitaramc/gitolite
  14. Since gitolite administration is based on keys and we used windows machines to connect to the linux servers, we used putty to generate keys for every user. Copy-paste the text from puttygen as USERNAME.pub and save the private key as USERNAME.ppkThe .pub key will have to be uploaded by gitolite admin to the gitolite repos which the USERNAME will have access.

    We used this tutorial for our first install, what’s really important to keep in mind is that there are two machines in use: one is the server (linux server) and the other is the client (in the tutorial I’ve linked the client is also a linux box; in our scenario the clients were windows machines).

    It’s important to note that for the first use of gitolite, you have to create the .pub/.ppk pair of keys for the client user which will be the gitolite admin (so you’ll create this keys on the client machine, may that be linux, windows, w/e) and copy the .pub key into the git folder from the Server machine and give it proper permissions. Let’s say it will be git-admin.pub and git-admin.ppk like in the tutorial link above.
    Then, after you’ll install gitolite by logging in as user git onto the server machine, you’ll use the git-admin.pub key as argument to the initial setup of gitolite, like this:

    gitolite/install -ln
    gitolite setup -pk Git-Admin.pub
  15. Since we used windows machines to develop on, we installed git client on them and gitextensions also.For the git installer setup  we used the following options:
    – advanced context menu, associate .git
    – use git bash only
    – use plink
    – checkout windows style, commit linux style

    And for the gitextensions setup we used the following options:
    – install kdiff only
    – use putty
    – (dumb observation: sometimes the kdiff installer windows pops under the main gitextensions installer window and at first sight it seems the main installer hanged; it didn’t, it just awaits for your action on the windows behind)

  16. We also had an interesting setup where our git server would automatically deploy upon receive, on the httpd test server installed on the same machine. We used a script placed in hooks/post-receive folder with the following content:
    export GIT_WORK_TREE
    umask 002
    git checkout -f

    The script has to have proper permissions.
    Also, the www folder should be owned by apache user and have the group set to apache group and the git user should be added to the apache group.

    chmod +x hooks/post-receive
    chown apache:apache /home/path/to/your/www
    usermod --groups apache git

    Also, you have to init a new empty repo into the www folder

    cd /home/path/to/your/www
    mkdir newfolder
    cd newfolder
    git init
  17. After this, you can create new repos on the git server machine, from the client machine, by using the gitolite-admin repo.You must clone first the admin repo (git clone gitolite-admin.git) on your client machine and then use this repo as a setup tool for the repos you wanna create and manage.You can create new git repos, add users to those repos by putting their pub keys into the keys folder and setting up the gitolite.conf file.

    Every time you push the changes for the gitolite-admin repo, the new keys will be uploaded to server and gitolite.conf changes taken into consideration and this will basically be your tool to manage the git repos on the (test) server machine.

    A very good tutorial which we initially used when setting gitolite can be found here: http://sachinsharm.wordpress.com/2013/10/04/installsetup-and-configure-git-server-with-gitolite-and-gitweb-on-centosrhel-6-4/ 



External links for reference, used in this article:

remi repo: http://www.rackspace.com/knowledge_center/article/installing-rhel-epel-repo-on-centos-5x-or-6x
webtatic repo: http://webtatic.com/projects/yum-repository/
yum-priorities: http://wiki.centos.org/PackageManagement/Yum/Priorities
simple tutorial on lamp install: https://www.digitalocean.com/community/articles/how-to-install-linux-apache-mysql-php-lamp-stack-on-centos-6
about gitolite: http://gitolite.com/gitolite/index.html
large tutorial on git and gitolite: http://sachinsharm.wordpress.com/2013/10/04/installsetup-and-configure-git-server-with-gitolite-and-gitweb-on-centosrhel-6-4/
git clients: http://git-scm.com/downloads
gitextensions for windows: https://code.google.com/p/gitextensions/
good info on how to auto-deploy from git server: http://stackoverflow.com/questions/9132144/how-can-i-automatically-deploy-my-app-after-a-git-push-github-and-node-js
if you want to install phpmyadmin via yum: http://tecadmin.net/how-to-install-phpmyadmin-on-centos-using-yum/
in case you get httpd dead but subsys locked error: http://sandzoctanium.com/upgrade-from-php-5-3-to-php-5-5-and-get-error-httpd-dead-but-subsys-locked/


Job Interview Quick questions and answers

Here’s a list of quick questions and answers you may find when going to a PHP Job Interview.

1. $name vs $$name
Answer: $name is a variable and $$name is a reference variable.

2. What is the difference between Classes and Interfaces?
Answer: Interfaces do not contain business logic; they only contain method signatures that define a template which all the classes implementing the interface must contain.

interface animal{
	function breath();
	function eat();
class dog implements animal{
	function breath(){
		echo 'breath';
	function eat(){
		echo 'eat';
	function bark(){
		echo 'ham! ham!';

3. What is the difference between include(); and require(); ?
Answer: include(); throws a warning if the included file cannot be accessed and require(); throws a fatal error.

4. How to encrypt and decrypt data with mysql?
Answer: by using AES_ENCRYPT(); and AES_DECRYPT();

5. What is a well-formed XML document?
Answer: It’s a document which adheres to the syntax rules specified by XML 1.0:
– content is defined
– content is delimited with beginning and end tags
– content is properly nested
– contains only properly encoded legal Unicode chars
– has no overlapping tags
– tags are case-sensitive, cannot start with numbers, minus, point and cannot contain the following !”$@()+/<>=?\[]

6.What is a valid-document XML?
Answer: A valid XML is a well-formed document which has DTD (Document Type Definition)

7. Enumerate Access Modifiers
– public => anyone can access the item
– protected => only the same class and children of it can access
– private => only the same class can access
– final => cannot be overridden in the children classes
– abstract => cannot be used directly, it must be inherited from it first

8. Give example of simple external XML DTD
<!ELEMENT people_list(person)*>
<!ELEMENT person(name,birthdate?)>
<!ELEMENT birthdate(#PCDATA)>

* => there can be zero or more person elements
? => optional elements
#PCDATA => parsed character data

9. What are objects in OOP?
Answer: Objects are instantiated classes.

10. Name couple design patterns.
– factory
– singleton
– strategy
– decorator

Btw, here are some great articles on design patterns: Five design patterns and Five more design patterns

11. Describe what MVC initials stand for, in short.
model =>
– representation of actual data
– data access code
– business logic code

view =>
– contains mark-up and design code

controller =>
– controls the actions to be executed
– calls the models
– renders the views
– defines what the data is

12. What do you know about the STATIC keyword?
Declaring class properties or methods as static makes them accessible without needing an instance of the class.
STATIC can also be used to define static variables and for late static bindings.
Because static methods are callable without an instance of the object created, the pseudo-variable $this-> is not available inside the method declared as static.

13. What are Static Variables?
Answer: A static variable exists only in a local function scope, but does not loose it’s value when the program execution leaves this scope.

14. What about Late Static Bindings?
– reference the called class in a context of static inheritance
– available since PHP 5.3.0
– example.: static::call();

15. How php session works?
– a php session cookie is set in client browser
– on every request, the client sends that cookie to the server
– php uses that cookie to select corresponding session information

16. Big changes in PHP lately?
– PHP 5.0 added OOP
– PHP 5.1 added PDO
– PHP 5.3 added namespace and late static bindings

17. Differences between $_GET and $_POST
Every HTTP request contains a method, generally GET, PUT, POST, DELETE.

HTTP is an application protocol. It functions as a request-response protocol in the client-server computing model.

HTTP defines methods to indicate the desired action to be performed on the identified resource
=> GET – requests a representation of the data
=> HEAD – asks for the same response as GET without the body
=> POST – requests the server to accept the entity enclosed as a new subordinate of the resource
=> PUT – requests the enclosed entity to be stored under the supplied URI
=> DELETE – deletes the resource

* PUT vs POST => idempotent != non-idempotent

The fundamental difference between PUT and POST is reflected in the different meaning of the Request URI.

In POST, the URI identifies the resource that will handle the enclosed entity.

In PUT, the URI identifies the entity enclosed with the request.

POST may changes other entities.
PUT may change only the enclosed entity.

PUT = idempotent, aka calling PUT multiple times with the same data does nut further changes the data.

An object can take on many forms.
A class CAR can have 2 classes that extend it, a class Honda and a class BMW.

18. How to autoload classes in PHP?
By using spl_autoload_register(); it allows multiples autoloaders to be registered.

function my_autoloader($class){
	include 'classes/'.$class.'.class.php';

19. How to do a classic, basic, file upload (no need to write security or checks)

if($_FILES["file"]["error"] == 0){
	move_uploaded_file($_FILES["file"]["tmp_name"], "upload/".$_FILES["file"]["name"]);

20. How to create a file in php?
Answer 1:

$filename = 'some-file.txt';
if(($file = fopen($filename,"w")) == false)
fwrite($file, "some content here");

Answer 2:

file_put_contents('filename.txt', 'some content here');

21. What does SHARDING mean?
Sharding means splitting a database into several pieces, usually to improve the speed and reliability of the application.

Sharding is a synonym for “horizontal partitioning” or dividing a table by it’s rows.

In common use, sharding refers to having data split onto multiple servers.

Partitioning a tables splits the table by rows, usually on a singe instance of schema and database server.

Sharding a table splits a table across (potentially) multiple servers (physical or logical).

22. Why would you user ORDER By NULL?

When using GROUP BY, mysql sorts group by col1, col2 as if you’ve requested ORDER BY col1, col2.

If you want to suppress the sorting, you can specify ORDER BY NULL.

22. How to swap the content of two variables x,y with no other variable?
Answer 1:

$x=27; $y=78;
$x = $x + $y;
$y = $x - $y;
$x = $x - $y;

Answer 2:

$x=27; $y=78;
$x = $x ^ $y;
$y = $x ^ $y;
$x = $x ^ $y;

23. Explain the differences between MySQL JOIN types.

INNER JOIN => an output row is produced for every pair of input rows that match on the join conditions.

LEFT JOIN => same as above, except that if there is any row for which no matching row can be found in the table on the right, an output is generated with the values from the left table, with NULL for each value in the table in the right.

RIGHT JOIN => same as LEFT JOIN, but roles reversed.

FULL JOIN => a combination of left and right; every row from both tables will appear at least once in the output

CROSS JOIN => INNER JOIN without conditions, resulting in all pairs of rows being output.

24. How to free memory in PHP? How to measure it?
– unset(); marks a variable for garbage collection, but the stack remains at the current value.
– setting the variable to NULL drops the data and shrinks the stack memory.

– memory_get_peak_usage(); and memory_get_usage();

25. Describe database normalization
Normalization is the process of organizing efficiently data in a database.
– eliminate redundant data
– only store related data in a table.

The normal forms (NF)

1. First Normal Form (1NF)
– eliminate duplicate columns from the same table
– create separate table for each group of related data and identify each row by PK

2. Second Normal Form (2NF)
– remove subsets of data that apply to multiple rows of a table and place them in a separate table
– create relationships between these new tables and their predecessors trough the use of FK

3. Third Normal Form (3NF)
– remove columns that are not dependent upon the primary key

4. Boyce-Cold Normal Form (3.5NF)
– every determinant must be a CK (Candidate Key)

5. Fourth Normal Form (4NF)
– a relation is in 4NF if it has no multi-valued dependencies

a. Candidate Key
– a candidate key is a combination of attributes that can be uniquely used to identify a database record without any extraneous data.
– each table may have one ore more CK
– one of these CK is the PK

b. Multi-valued dependencies
– MV dependencies occur when the presence of one or more rows in a table implies the presence of one or more other rows in that same table.