Introduction

When deciding which server architecture to use for your environment, there are many factors to consider, such as performance, scalability, availability, reliability, cost, and ease of management.

Here is a list of commonly used server setups, with a short description of each, including pros and cons. Keep in mind that all of the concepts covered here can be used in various combinations with one another, and that every environment has different requirements, so there is no single, correct configuration.

1. Everything On One Server

The entire environment resides on a single server. For a typical web application, that would include the web server, application server, and database server. A common variation of this setup is a LAMP stack, which stands for Linux, Apache, MySQL, and PHP, on a single server.

Use Case: Good for setting up an application quickly, as it is the simplest setup possible, but it offers little in the way of scalability and component isolation.

Pros:

Simple

Cons:

Application and database contend for the same server resources (CPU, Memory, I/O, etc.) which, aside from possible poor performance, can make it difficult to determine the source (application or database) of poor performance

Not readily horizontally scalable

2. Separate Database Server

The database management system (DBMS) can be separated from the rest of the environment to eliminate the resource contention between the application and the database, and to increase security by removing the database from the DMZ, or public internet.

Use Case: Good for setting up an application quickly, but keeps application and database from fighting over the same system resources.

Pros:

Application and database tiers do not contend for the same server resources (CPU, Memory, I/O, etc.)

You may vertically scale each tier separately, by adding more resources to whichever server needs increased capacity

Depending on your setup, it may increase security by removing your database from the DMZ

Cons:

Slightly more complex setup than single server

Performance issues can arise if the network connection between the two servers is high-latency (i.e. the servers are geographically distant from each other), or the bandwidth is too low for the amount of data being transferred

3. Load Balancer (Reverse Proxy)

Load balancers can be added to a server environment to improve performance and reliability by distributing the workload across multiple servers. If one of the servers that is load balanced fails, the other servers will handle the incoming traffic until the failed server becomes healthy again. It can also be used to serve multiple applications through the same domain and port, by using a layer 7 (application layer) reverse proxy.

Use Case: Useful in an environment that requires scaling by adding more servers, also known as horizontal scaling.

Pros:

Enables horizontal scaling, i.e. environment capacity can be scaled by adding more servers to it

Can protect against DDOS attacks by limiting client connections to a sensible amount and frequency

Cons:

The load balancer can become a performance bottleneck if it does not have enough resources, or if it is configured poorly

Can introduce complexities that require additional consideration, such as where to perform SSL termination and how to handle applications that require sticky sessions

4. HTTP Accelerator (Caching Reverse Proxy)

An HTTP accelerator, or caching HTTP reverse proxy, can be used to reduce the time it takes to serve content to a user through a variety of techniques. The main technique employed with an HTTP accelerator is caching responses from a web or application server in memory, so future requests for the same content can be served quickly, with less unnecessary interaction with the web or application servers.

5. Master-Slave Database Replication

One way to improve performance of a database system that performs many reads compared to writes, such as a CMS, is to use master-slave database replication. Master-slave replication requires a master and one or more slave nodes. In this setup, all updates are sent to the master node and reads can be distributed across all nodes.

Use Case: Good for increasing the read performance for the database tier of an application.

Here is an example of a master-slave replication setup, with a single slave node:

Pros:

Improves database read performance by spreading reads across slaves

Can improve write performance by using master exclusively for updates (it spends no time serving read requests)

Cons:

The application accessing the database must have a mechanism to determine which database nodes it should send update and read requests to

Updates to slaves are asynchronous, so there is a chance that their contents could be out of date

If the master fails, no updates can be performed on the database until the issue is corrected

Does not have built-in failover in case of failure of master node

Example: Combining the Concepts

It is possible to load balance the caching servers, in addition to the application servers, and use database replication in a single environment. The purpose of combining these techniques is to reap the benefits of each without introducing too many issues or complexity. Here is an example diagram of what a server environment could look like:

Let’s assume that the load balancer is configured to recognize static requests (like images, css, javascript, etc.) and send those requests directly to the caching servers, and send other requests to the application servers.

Here is a description of what would happen when a user sends a requests dynamic content:

app-backend reads from the database and returns requested content to load balancer

The load balancer returns requested data to the user

If the user requests static content:

The load balancer checks cache-backend to see if the requested content is cached (cache-hit) or not (cache-miss)

If cache-hit: return the requested content to the load balancer and jump to Step 7. If cache-miss: the cache server forwards the request to app-backend, through the load balancer

The load balancer forwards the request through to app-backend

app-backend reads from the database then returns requested content to the load balancer

The load balancer forwards the response to cache-backend

cache-backend caches the content then returns it to the load balancer

The load balancer returns requested data to the user

This environment still has two single points of failure (load balancer and master database server), but it provides the all of the other reliability and performance benefits that were described in each section above.

Conclusion

Now that you are familiar with some basic server setups, you should have a good idea of what kind of setup you would use for your own application(s). If you are working on improving your own environment, remember that an iterative process is best to avoid introducing too many complexities too quickly.

Let us know of any setups you recommend or would like to learn more about in the comments below!

About SSH Keys

SSH keys provide a more secure way of logging into a virtual private server with SSH than using a password alone. While a password can eventually be cracked with a brute force attack, SSH keys are nearly impossible to decipher by brute force alone. Generating a key pair provides you with two long string of characters: a public and a private key. You can place the public key on any server, and then unlock it by connecting to it with a client that already has the private key. When the two match up, the system unlocks without the need for a password. You can increase security even more by protecting the private key with a passphrase.

Step One—Create the RSA Key Pair

The first step is to create the key pair on the client machine (there is a good chance that this will just be your computer):

ssh-keygen -t rsa

Step Two—Store the Keys and Passphrase

Once you have entered the Gen Key command, you will get a few more questions:

Enter file in which to save the key (/home/demo/.ssh/id_rsa):

You can press enter here, saving the file to the user home (in this case, my example user is called demo).

Enter passphrase (empty for no passphrase):

It’s up to you whether you want to use a passphrase. Entering a passphrase does have its benefits: the security of a key, no matter how encrypted, still depends on the fact that it is not visible to anyone else. Should a passphrase-protected private key fall into an unauthorized users possession, they will be unable to log in to its associated accounts until they figure out the passphrase, buying the hacked user some extra time. The only downside, of course, to having a passphrase, is then having to type it in each time you use the Key Pair.

The authenticity of host '12.34.56.78 (12.34.56.78)' can't be established.
RSA key fingerprint is b1:2d:33:67:ce:35:4d:5f:f3:a8:cd:c0:c4:48:86:12.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '12.34.56.78' (RSA) to the list of known hosts.
user@12.34.56.78's password:
Now try logging into the machine, with "ssh 'user@12.34.56.78'", and check in:
~/.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.

Now you can go ahead and log into user@12.34.56.78 and you will not be prompted for a password. However, if you set a passphrase, you will be asked to enter the passphrase at that time (and whenever else you log in in the future).

Optional Step Four—Disable the Password for Root Login

Once you have copied your SSH keys unto your server and ensured that you can log in with the SSH keys alone, you can go ahead and restrict the root login to only be permitted via SSH keys.

In order to do this, open up the SSH config file:

sudo nano /etc/ssh/sshd_config

Within that file, find the line that includes PermitRootLogin and modify it to ensure that users can only connect with their SSH key:

The <canvas> element has been a revelation for the visual experts among our ranks. Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead. Here are nine unbelievable canvas demos that will make your jaw drop!

1. Zen Photon Garden

The Zen Photon Garden demo is the epitome of mind-blowing. This epic canvas demo allows for drawing on the canvas with reactive light streams, allowing the user to see the end product of their new line will be. Even better, this demo allows you to save and load output.

2. Tear-able Cloth

The Tear-able Cloth demo has set the web alight over the past few months and for good reason. This demo is the smoothest you’ll see and considering the task it accomplishes and the how little code is involved, it will take your breath away. There’s more to it than simple pulling and physics — the animation and needing to account for pulling hard enough to elegantly animate a tear makes this demo even more amazing. A perfect illustration of canvas’ capabilities.

4. Motion Graphic Typeface

I wish I could describe how this effect is done but I can’t. I see that each letter is comprised of different image data, but that’s about it. What I can say is this animation is absolutely mind-blowing, as letters animate into place and the aspect at which you see the text depends on your mouse position. Shocking.

5. Motion Graphic Typeface II

As if the first wasn’t impressive enough, the second MGT demo is one worthy of a Pulitzer Prize. I’d give up my second, third, and eighth-born to be this clever. Not only does the text animate but there’s an incredible colored blur that’s part of the animation. This demo is truly a sight to behold.

6. Gestures + Reveal.JS

Now only did this demo blow my mind, but it also blew my CPU. This exercise uses your device’s camera and microphone to move a cube of data based on gestures. If you have a MacBook Pro, you shouldn’t die before trying this out. Start the demo and flail your arms about — you’ll se the demo content move about and then start believing in spirits.

7. Free Rider 2

You can’t cover the awesomeness of canvas without including at least one game. Canvas is arguably the future of HTML5 gaming, as Firefox OS will soon demonstrate. This brilliant but simple bike game shows that canvas is ready for prime time!

8. 30,000 Particles

The 30k Particles demo incorporates some really awesome stuff: circular shapes (radius), animated exploding and returning particles, and mouse listeners to allow the user to control the explosions. An excellent example of interactivity and logic.

9. HTML5 Video Destruction

I must pay homage to one of the first truly eye-catching canvas demos I saw — an explodable canvas video. You click the video and pieces explode, yet the video keeps playing its segment/position during the explosion while it returns to its original position. An inspiring demo to to all of us.

In this post we will look into accessing Twitter REST API in PHP. This can be useful if you need to post Tweets from your PHP application or anaylze, search Tweets. In the following examples we will use the twitter-api-php PHP wrapper for Twitter v1.1 API. Although there are a few wrappers around, this one I like for its simplicity.

Installation

If you use composer, here’s what you need to add to your composer.json file to have TwitterAPIExchange.php (Twitter PHP wrapper) automatically imported into your vendor’s folder:

{
"require": {
"j7mbo/twitter-api-php": "dev-master"
}
}

You’ll then need to run ‘composer install’.

If you don’t use composer, just download the zip from git and include TwitterAPIExchange.php in your application path.

Registering your Twitter app

Before writing any code, you will first need to create a Twitter app and register it onhttps://apps.twitter.com/. You will be greeted with the following screen. (The following screenshot shows you an existing app. If this is your first app than the page will be blank).

Click on the ‘Create New App’ button and enter the required details in the fields provided. Leave the ‘Callback URL’ field blank for now. Once the app is created, click on the app name and note down the various access and security tokens, we will be needing these later. Change your Access Level to ‘Read and Write’. ‘Read Only’ access does not allow you to update, add or delete Tweets. If your purpose is to only read tweet data, it is safer to set the Access Level to ‘Read Only’.

Note that you will need to regenerate the access tokens if you change the Access Levels anytime and modify the same in your PHP code.

Accessing the Twitter API from PHP

Now that you have created and registered a Twitter app, we can now use PHP to acccess the API. First include the ‘TwitterAPIExchange.php’ class and set various security tokens collected earlier.

For this example we will be using the ‘https://api.twitter.com/1.1/statuses/user_timeline.json‘ resource url. This returns a collection of the most recent Tweets posted by the user indicated by the screen_name or user_id parameters. This particular method is one of the dozens of various methods available to access and modify Twitter data; others can be found here.

A complete GET request method is shown below. Here we are requesting the recent 3 tweets for the user ‘johndoe123’.

Executing the above code will return the recent 3 tweets for the given user in JSON format. You can specify the number of tweets to return using the ‘count parameter. The maximum that can be returned is 200.

$getfield = '?screen_name=johndoe123&count=3';

Note that all GET fields for this method are optional. Not specifying any GET parameters will return 20 recent tweets for the current user, i.e the user with the given access tokens. You can query without the GET parameters as shown below.

API rate limits

One important point to consider when creating your app is of rate limiting. Twitter limits the rate at which you query using their API. For example search will be rate limited at 180 queries per 15 minute window. More information can be found here.

Important Note

If the above examples do not work you will have to make a small change in ‘TwitterAPIExchange.php’. The curl processing part (around line 192) requires the line ‘CURLOPT_SSL_VERIFYPEER => false,’ to be added. So the curl part in the file should read the following.

Sometimes you just need to start a video playing by some user interaction on the page other than clicking right on that video itself. Perhaps a “Play Video” button of your own creation lives on your page and you want to start that video when that button is clicked. That’s JavaScript territory. And if that video is a YouTube or Vimeo video, we’ll need to make use of the APIs they provide. No problem.

For these examples, we’ll assume you’ve already picked out a video and you’re going to put it on the page in an

3. Create a global function called onYouTubePlayerAPIReady

This is the callback function that the YouTube API will call when it’s ready. It needs to be named this.

function onYouTubePlayerAPIReady(){}

It’s likely you have some structure to your JavaScript on your page, so generally I’d recommend just having this function call another function that is inside your organizational system and get going on the right track right away. But for this tutorial, let’s just keep it soup-y.

4. Create the Player object

This is the object that has the ability to control that video. We’ll create it using the id attribute on that iframe in our HTML.

var player;function onYouTubePlayerAPIReady(){// create the global player from the specific iframe (#video)
player =new YT.Player('video',{
events:{// call this function when player is ready to use
'onReady': onPlayerReady
}});}

Another callback!

5. Create the “player ready” callback and bind events

We named this function when we created the player object. It will automatically be passed the event object, in which event.target is the player, but since we already have a global for it let’s just use that.

Here we bind a simple click event to an element on the page with the id #play-button (whatever custom button you want) and call the player object’s playVideo method.

For Vimeo

1. Make sure the iframe src URL has ?api=1 at the end

I also put an id attribute on the iframe so it will be easy and fast to target with JavaScript.

2. Load the “froogaloop” JS library

The Vimeo player API actually works by sending commands through postMessage right to the iframe. You don’t need the froogaloop library to do that, but postMessage has some inherent complexities that this library (by Vimeo themselves) makes way easier. Plus it’s only 1.8kb so I’d recommend it.

About Lemp

LEMP stack is a group of open source software to get web servers up and running. The acronym stands for Linux, nginx (pronounced Engine x), MySQL, and PHP. Since the server is already running Ubuntu, the linux part is taken care of. Here is how to install the rest.

Tutorial source – Digital Ocean

Setup

The steps in this tutorial require the user to have root privileges. You can see how to set that up in the Initial Server Setup Tutorial in steps 3 and 4.

Step One—Update Apt-Get

Throughout this tutorial we will be using apt-get as an installer for all the server programs. On May 8th, 2012, a serious php vulnerability was discovered, and it is important that we download all of the latest patched software to protect the virtual private server.

Let’s do a thorough update.

sudo apt-get update

Step Two—Install MySQL

MySQL is a powerful database management system used for organizing and retrieving data

To install MySQL, open terminal and type in these commands:

sudo apt-get install mysql-server php5-mysql

During the installation, MySQL will ask you to set a root password. If you miss the chance to set the password while the program is installing, it is very easy to set the password later from within the MySQL shell.

Once you have installed MySQL, we should activate it with this command:

Then the prompt will ask you if you want to change the root password. Go ahead and choose N and move on to the next steps.

It’s easiest just to say Yes to all the options. At the end, MySQL will reload and implement the new changes.

By default, a MySQL installation has an anonymous user, allowing anyone
to log into MySQL without having to have a user account created for
them. This is intended only for testing, and to make the installation
go a bit smoother. You should remove them before moving into a
production environment.
Remove anonymous users? [Y/n] y
... Success!
Normally, root should only be allowed to connect from 'localhost'. This
ensures that someone cannot guess at the root password from the network.
Disallow root login remotely? [Y/n] y
... Success!
By default, MySQL comes with a database named 'test' that anyone can
access. This is also intended only for testing, and should be removed
before moving into a production environment.
Remove test database and access to it? [Y/n] y
- Dropping test database...
... Success!
- Removing privileges on test database...
... Success!
Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.
Reload privilege tables now? [Y/n] y
... Success!
Cleaning up...

Once you’re done with that you can finish up by installing PHP.

Step Three—Install nginx

Once MySQL is all set up, we can move on to installing nginx on the VPS.

You can confirm that nginx has installed an your web server by directing your browser to your IP address.

You can run the following command to reveal your VPS’s IP address.

ifconfig eth0 | grep inet | awk '{ print $2 }'

Step Four—Install PHP

To install PHP-FPM, open terminal and type in these commands. We will configure the details of nginx and php details in the next step:

sudo apt-get install php5-fpm

Step Five—Configure php

We need to make one small change in the php configuration.Open up php.ini:

sudo nano /etc/php5/fpm/php.ini

Find the line, cgi.fix_pathinfo=1, and change the 1 to 0.

cgi.fix_pathinfo=0

If this number is kept as 1, the php interpreter will do its best to process the file that is as near to the requested file as possible. This is a possible security risk. If this number is set to 0, conversely, the interpreter will only process the exact file path—a much safer alternative. Save and Exit. We need to make another small change in the php5-fpm configuration.Open up http://www.conf:

sudo nano /etc/php5/fpm/pool.d/www.conf

Find the line, listen = 127.0.0.1:9000, and change the 127.0.0.1:9000 to /var/run/php5-fpm.sock.

listen = /var/run/php5-fpm.sock

Save and Exit.

Restart php-fpm:

sudo service php5-fpm restart

Step Six—Configure nginx

Open up the default virtual host file.

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

The configuration should include the changes below (the details of the changes are under the config information):

UPDATE: Newer Ubuntu versions create a directory called ‘html’ instead of ‘www’ by default. If /usr/share/nginx/www does not exist, it’s probably called html. Make sure you update your configuration appropriately.

This tutorial will show you how to create dynamic pages with php. As you know php is the best language to create dynamic website and today we are going to see how it’s done.

Step 1: Create files

First we need few separate pages so let’s go ahead and create few pages. First page we need is index.php that will be our main page, so create a page and name it index.php. After that we need to add some HTML to the page.

For now we will not specify any path in our links, we will get back to it later. Now if you have done everything alright you will get a page like this:

PHP Dynamic Page

Other pages:

Now that we are done with our main page, we want to create few other pages. So just create three pages and name them products.php , blog.php and about.php. After that we want to put some content in these pages, we don’t have to put all those HTML tags again. We will just have to put the content that we want to show on the website, so for product’s page put the following lines in the page.

<?php
echo "<h2>Products</h2>";
echo "This is our product page.<br/>";
echo "You should be able to see all of our products here.";
?>

Do same for other two pages. You can put in there whatever you like, just keep in mind one thing that you won’t have to put <html> tags again.

Step 2: Making Pages Dynamic

As we are done with our main page and we have created other pages, now its turn to make those pages dynamic. We will just have to change the url to get the requested page and after that use GET variable to catch the value and assign it to another variable. Then we can just print that variable and we will get all the content from other pages on our main page.

So basically what we have done here is, we have checked if the value in GET is set or not and if it is set we have assigned the value in GET to page variable and if it is not set we have set page variable equal to NULL.Secondly we need to add some code to our main page where we want to show the content of other pages. As we need to show the content of other pages after our navigation so put these line after closing ul tag.

Here we are checking if the page variable is empty then show the content of main page and if the page variable is not empty then we will include page variable. Basically the page variable contains our page which we want to show on our main page, don’t worry it will all make sense in a minute.

Changing Links:

After our main page is all set the last thing we need to do is to change our link in the main page. So just make these changes in the links of main page.

As you can see all these pages are referring to the index.php but here our concern is the part after the index.php that is the part after ?. After ? we are using a variable or you can say reference name ‘page’, you can use any name here but you will have to change the GET variable too. We are taking page equal to our required page.

After it’s all set you can try it and hopefully it will work.

PHP Dynamic Page

PHP Dynamic Page

PHP Dynamic Page

Step 3: Improving Links

You can take it one step farther by modifying the code little bit and making your link more attractive instead of index.php?page=about.php. So what you need to do is add a line right after where you are assigning GET variable value to page in index page.

Now when you will browse to any of these links it will not show .php and your link will look more lively like index.php?page=about. We are done and now you can play a little bit more if you want with your pages. Go ahead and try this and leave a comment if you get stuck anywhere or want to share something new.