Configuring PHP + MySQL + Apache on Amazon EC2 Step by Step

Log in to
Click on EC2 virtual servers in the cloud

From the left menu, under Network and Security, select Key Pairs
Create on by hitting “Create Key Pair”. Mind you, aws will give you only one chance to save the pem file you will be using for logging. So make sure you download and save it.

From your select Elastic Beanstalk and follow the wizard to create an instance per your need.
in the wizard, there is a step you will be asked to use the pem file you downloaded.

Now from the left menu, click on the instances.
And click on the instance on the right pane and you will see another pane with description will be opened on the lower part. On that pane, search for security group and click the link
You will be transferred to the security group associated with that instance. Click on the “in bound” tab and check if SSH is listed there, if not, hit the ‘Edit’ button and add a new rule of SSH with the source of anywhere if you would like to ssh into your box from anywhere or you can specify particular ip address.

log to your instance from terminal as

ssh -i /your/downloaded/pem/file ec2-user@public-domain-goes-here

you will get your public domain on the instance you selected.

If you are using Elastic Beanstalk, it will come with installed apache server for as your webserver. Just restart it

sudo service httpd restart

MySQL shell would be there as well but not the mysql server so install that

sudo yum install -y mysql-server

And restart the demon

sudo service mysqld restart

I have checked if git is installed, if you are using any DCVS, which you should and it is installed already to verify do

git --version

Next would be the creation of your public and private keys for secure communication with the other servers.

ssh-agent -t rsa -b 4096 "your_email@domain.tld"

The above command will provide you with the public and private key that you would use. The default path for it would be on ~/.ssh/id_rsa and ~/.ssh/

If you are using github or bitbucket, you would need the content of the for logging to the server without password.

If you are going to use mongo just use the very information on the following links

This will get you started with your aws instance

Adding session bean to to requested bean using annotation JSF

One major part on JSF would separation of concerns even for beans. As a rule of thumb beans related to model are session beans and those which have actions to be taken care of are requested one.

So, In this particular scenario we would have two beans. Basically we don’t want to include any logic inside the session bean, rather we would add session bean as a member variable to request bean.

Lets take a simple registration process.

The requested bean which will be responsible for actions would look like

package com.enderase.beans;


import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;

import com.enderase.model.Contractor;

public class ActionListeners implements Serializable{
	private Contractor contractor;
	public void setContractor(Contractor contractor){
		this.contractor = contractor;
	public Contractor getContractor() {
		return this.contractor;
	private static final long serialVersionUID = 1L;
	 * Action handler for Contractor save.
	 * @return String, next
	public String registerContractor() {
		Contractor contractor = this.contractor;
		if (contractor != null) {
			try {
				FileWriter fileWriter = new FileWriter("/tmp/name.note");
				BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
				bufferedWriter.write("Name "+contractor.getName()+" Email "+contractor.getEmail()
			} catch (Exception ex) {
				//log the exception here
		return "navigated";

So the key thing here would be the @ManagedProperty part.
That would inject the session bean into the request bean without creating any instance of it.

*Don’t for get to add getter and setter for the session bean you are adding otherwise you would get an error.

The session bean would be a simple holder of model

package com.enderase.beans;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import com.enderase.model.Contractor;

public class ContractorBean {
	private Contractor contractor;
	public ContractorBean() {
		this.contractor = new Contractor();
	public Contractor getContractor(){
		return this.contractor;
	public void setContractor(Contractor contractor){
		this.contractor = contractor;

Where the contractor would be a simple POJO file

Debugging PHP app using xDebug and Eclipse Tutorial

This will be a tutorial on how to debug a PHP application using xDebug and eclipse.

1. Get the eclipse for php from Eclipse for php
A side note, if you are on any *nix OS, this might require you to update your java to 1.7 and above. If that is the case, download latest Java JDK from Oracle (1.8 at the time of writing) and do:

which java

in most cases, this will show /usr/bin/java which is a symlink to the actual java binary.
Follow the symlink using

ls -la 

That depending on the destro you have, would point to the link destination, there you can point to the java symlink to

ln -s /path/to/the/downloaded/jdk/bin/java

That should take care of the problem.
On windows, you need to updateh environment variable that you set for the JAVA_HOME. Googling on this shall give you the right direction.

2. Get xDebug on your system
Well, before this you might need the whole stack of apache, or any other php-approved webserver, and php itself. For that if you are on *nix you can use

sudo apt-get install lamp-server^

On windows, you can use wamp server and be done with it.

To install xdebug on *nix

sudo apt-get install php5-xdebug

Once you do that, restart your apache server

service apache2 restart

and do phpinfo(); you should be able to see the xdebug info there.

Now, pull your php.ini and add the following to it


You can alternately add this info in the xdebug.ini if it it exists in the additional ini folder. This information would be available on the phpinfo();

Again restart your apache web server.

For testing purposes I have created a simple yet good php example on

Go to your eclipse Run>Run Configurations..
and do the following on respective tabs
For server tab:

For Debugger tab.


Now your eclipse is ready for debugging!
You can put a break point by double clicking on the area you would like the debugger to stop.
As you can see, I was able to see the value assigned on the $config variable that is was read from config.ini file.


the requested PHP extension mongo is missing from your system.

Got this error when trying to add the mongodb stuff your php project – specially using composer then here is how to solve it.

The first thing is you have to add the mongodb driver to php.

You might need PEAR on your system. Adding pear to your system is relatively easy and google can help on that.

Then do the following on your terminal

sudo pecl install mongo
pecl install mongo

The last lines of successful installation would tell where the installation has occurred and some more important information.

Now you need to add the to the php.ini

if you don’t know where you have php.ini run (on ubuntu)

locate php.ini

then run

echo "" >> path-to-php.ini

file upload

multiple file upload in Symfony2 example

Multiple File Upload in Symfony framework

I spent decent amount of time to put together the multiple file upload in symfony.

It is not that difficult actually but the problem is there is no direct/easy documentation or tutorial on it.

On the form type where you would build the form, have the files with the type of collection and make its type a file entity. In this case there would be two file types by default.

    public function buildForm(FormBuilderInterface $builder, array $options) 
         * The file does not need to be added as "file" because it is referred
         * in the validation for File and SF will automatically know it is file.
        return $builder
                ->add("files", 'collection', array(
		    'type'=>new FileType(),
		    'data'=>array(new BundleEntityFile(),
		    new BundleEntityFile())
                ->add('save', 'submit');

    public function getName()
        return "files";

The trick is on adding the files as collection. Initially, we have two file inputs and their type being FileType.

The allow_add is important to be able to add files through javascript.

The javascript would look like:

/*Handling multiple picture upload*/
    var total_files=$("#member_pictures_container li").length;
    var file_label=document.createElement("label");
    var div_file=document.createElement("div");    
    var picture= document.createElement('input');"PhotoAndDescription[files]["+total_files+"][file]";
    var list_element=document.createElement('li');

FileType would look like:

class FileType extends AbstractType
    public function buildForm(FormBuilderInterface $builder, array $options)
        return $builder->add("file", "file");

    public function getName()
        return "filetype";

    public function setDefaultOptions(OptionsResolverInterface $resolver)


And the twig file would look like this one

    {{ form_errors(form) }}
    {{ form_widget(form.about_member) }}
    • {% for file in form.files %}


  • {{ form_errors(file) }} {{ form_widget(file) }}



{% endfor %} {{form_end(form)}}

Pretty much this will take care of the multiple file handling in symfony2. As I mentioned earlier, it is not that difficult but the lack of documentation has made it so..

Do you know what to check to deploy Symfony app?

What is POST and HTTP-RAW-POST and php input has to do with enctype? Find out here

binary tree problems with solution

today is saturday and was catching upon some blogs. Then come across some binary tree algorithms and it reminded me the famous stanford binary tree questions.. decided to work on those and got to the mid of it..
Actually the questions get harder as you go further.. the first 7 are relatively easy..
I will continue to work on them and post my solution here.
the solutions are given on the this page but, it is advisable to work them out without looking a the solution..

here it is!

 * @author
 * binary tree problems and solutions.
struct Node
	int number;
	struct Node *left;
	struct Node *right;

int minValue(struct Node *head);
int maxDepth(struct Node *head);
int countNode(struct Node *head);
void printTree(struct Node *head);
void postOrderTraversal(struct Node *head);
struct Node *createNode(int value);
int hasPathSum(struct Node *head, int sum);
struct Node *head = NULL;
struct Node *head2=NULL;
int main()
	struct Node *head=createNode(10);
	struct Node *left=createNode(8);
	struct Node *right=createNode(15);
	struct Node *right1=createNode(5);
	struct Node *right2=createNode(1);

	struct Node *head2=createNode(5);
	struct Node *two=createNode(2);
	struct Node *seven=createNode(7);
	struct Node *eleven=createNode(11);
	struct Node *lfour=createNode(4);
	struct Node *thirteen=createNode(13);
	struct Node *eight=createNode(8);
	struct Node *rfour=createNode(4);
	struct Node *one=createNode(1);

	printf("Size of the tree is %d n", countNode(head));
	printf("Max depth is %d n", maxDepth(head)-1);
	printf("Minimum Value is %d n", minValue(head));
	int hasSum = hasPathSum(head2,17);
		printf("it has sum");
		printf("it does not has sum");
	return 0;

 * Takes the head of the binary tree and counts how many children are there in the tree
 * it will recursively count the left and right nodes to come to the conclusion
int countNode(struct Node *head)
	if (head==NULL)
		return 0;
	return countNode(head->left)+1+countNode(head->right);

 * Finds the maximum depth of the tree
int maxDepth(struct Node *head)
	int maxLength = 0;
	if (head==NULL)
		return 0;
		int leftMax = 1 + maxDepth(head->left);
		int rightMax = 1 + maxDepth(head->right);
		if (leftMax > rightMax)
			return leftMax;
		return rightMax;

 * Works on the Binary Search Tree - since on the BST, for sure the left child is always lesser in value.
int minValue(struct Node *head)
		return 0; //might not be valid answer here
	struct Node *current=head;
	return current->number;

 * Prints the value of the BST
 * this is inorder traversal
void printTree(struct Node *head)
	if (head==NULL)
		printf("%d, ", head->number);

int hasPathSum(struct Node *head, int sum)
	int localsum = 0;
	if (head == NULL)
		return 0;
	else if(head->left==NULL && head->right==NULL)
		return (sum-head->number == 0);
		int temp=sum-head->number;
		return hasPathSum(head->left, temp) || hasPathSum(head->right, temp);
 * Post order traversal version of the tree traversal
void postOrderTraversal(struct Node *head)
	if (head==NULL)
		printf("%d, ", head->number);

 * Create new node
struct Node *createNode(int value)
	struct Node *newNode=malloc(sizeof(struct Node));
	return newNode;

Assembly code example – square a number

Here is another example of assembly code that would square a number:

#Simple square function in assembly language for x86 architecture
.code32 #tell the assembler we are using 32bit

.section .data #we don't have nothing in the data section
.section .text

.globl _start

    push $9 #fixed value of 9
    # The call updates the eip - instruction pointer
    call square 

    mov %eax, %ebx #the return value would be on register %eax, so pass it on %ebx
    mov $1, %eax #system call for exit on eax register - that would be 1
    int $0x80 #interupt

.type square, @function
    mov 4(%esp), %eax #read the value to square basing from the stack pointer (esp)
    imul %eax, %eax # umm.. whatelse? multiply the value and store it on eax
    ret #return the value 

do the following from the command line to run the code

$ gcc -m32 -nostartfiles -o square square.s 
$ ./square 
$ echo $?

Shall produce 81 on the command prompt

Dynamically populate select box from JSON in javascript/jQuery

Populating select box with JSON tutorial example

JSON [JavaScriptObjectNotation] has become the defacto standard for web-consumers these days.

I also interact with it in a frequent manner.

The major usage might be when you are interacting with API based websites. Even though there are multiple response types, json is one of the most widely endorsed these days.

Based on the response you can apply it to different parts of the web app.

When would I be using json for select boxes?

Lets say you are calling an API to give you the list of available cars and the API would return the result in json format.

Then you can use that response as a selection in select box or you can also list it as options to be checked in the form of checkboxes and the like.

Node tutorial with http web server

Here is example of using json response used in select box

I will try to give some simple example on using JSON with old school javascript and jquery.
Lets have the following JSON for our example:

var cars=[{"color":"red","made":"toyota","model":"corrola","mileage":"10000"},{"color":"silver","made":"honda","model":"accord","mileage":"160000"},{"color":"white","made":"nissan","model":"maxima","mileage":"12200"}];

Just ordinary simple data to play with.

Using Old School Javascript:

Assuming there is select box with id “dynamic_slct”

var options = '';
slctbox = document.getElementById('dynamic_slct');
for(var i=0 ; i<cars.length ; i++)
    var label = cars[i]['made'];
    var model = cars[i]['model']; //or whatever the value you want to show
    var opt = document.createElement('option');
    slctbox.options.add(new Option(label, model));

As simple as that, the ‘cars’ should be available on the page being accessible to the javascript that is populating the options. If you are working on PHP, for example, spitting the json_encode(array) would provide what is needed for this

Uisng jQuery

var opt="";
$.each(cars, function(){
   var label = this['made'];
   var model = this['model'];
   opt += ""+model+"";