Archive for August, 2009

Create Virtual Hosts and run multiple websites on Amazon server

You can create virtual hosts on any Linux or window platform if you are using Apache web server. Virtual hosts or v-hosts is basically Apache feature. I’m considering here Amazon server running with Apache version 2 or above. So, basically for creating v-hosts you need to modify Apache’s configuration (httpd.conf) file. You need the root access for all this modifications. Here I’m showing how we create the “name-based virtual hosting“. This is the easiest way of creating virtual host.
On Amazon server httpd.conf is located on ‘/etc/httpd/conf/httpd.conf‘ location. You need to follow these steps:-

1. First, take the backup of this file so in case if anything goes wrong you can rollback changes.
2. Download this file in your local machine and open it in any text editor.
3. Go to section 3 (Virtual Hosts) of this document.

### Section 3: Virtual Hosts

4. Un-comment this line

NameVirtualHost *:80

5. Now create v-hosts like this

<VirtualHost *:80>
    ServerAdmin admin@mydomain1.com
    DocumentRoot /var/www/html/domainname1
    ServerName www.domainname1.com
    ErrorLog logs/www.domainname1.com-error_log
    CustomLog logs/www.domainname1.com-access_log common
</VirtualHost>
<VirtualHost *:80>
    ServerAdmin admin@mydomain2.com
    DocumentRoot /var/www/html/domainname2
    ServerName www.domainname2.com
    ErrorLog logs/www.domainname2.com-error_log
    CustomLog logs/www.domainname2.com-access_log common
</VirtualHost>

Here we have create two virtual host one www.domainname1.com and second one www.domainname2.com. We have specified 5 Apache directive into a VirtualHost container. We can put almost any Apache directive into a VirtualHost container. Let’s discuss each one by one.

ServerAdmin – Here we specified email address of server administrator. If there is any issue Apache show this email address for contact.
DocumentRoot – Here we give the absolute path of directory where our website files are located.
ServerName – Here we give the name of our domain which is pointed to “/var/www/html/domainname1″ directory.
ErrorLog – Absolute path of Error log file for this domain.
CustomLog – Absolute path of custom log file for this domain.

6. Restart the Apache web server to apply these changes.
You can restart your Apache server using Terminal or Putty on Windows.

service httpd restart

Note:- One more thing which you need to do is you need to point both the domains “www.domainname1.com” and “www.domainname2.com” to the IP address of the Amazon server.

The Apache server it self find out the domain name form request header and point the incoming request to correct “DocumentRoot” directory.

, , ,

3 Comments


Initialize LightBox using JSON string and Run it from Flash

Lightbox is the most popular way of showing large image on click on thumbnail over the web. Lot of websites are using the LightBox. Normally, We use lightbox using the “rel” attribute of anchor tag. We use lightbox this way:-

<a href="images/image-1.jpg" rel="lightbox" title="thumb"><img src="images/thumb-1.jpg" width="100" height="40" alt="" /></a>

Here, we provided the “rel” attribute as “lightbox” in hyperlink. What lightbox script do is when page load completed its check all the hyperlinks of page and if rel=”lightbox” is exists them it push this link into an array.
Lightbox extract the “href” and “title” attributes of each link having rel=”lightbox” and push all of them into array. “href” is normally the URL of larger image. Lingtbox also add “click” event on all of these hyperlinks and when user click on any particular thumbnail the lightbox starts.

Here, I’m showing a way in which you can initialize the lightbox by using the JSON string. Basically, this JSON string contains the “href” and “title” information which we want to show. We can create this string dynamically using any server side scripting language. Here is one of sample JSON string.

<script language="javascript">
	var img_json = [['pics/photo-80.jpg', 'Title 01'],['pics/photo-128.jpg', 'Title 02'],['pics/photo-160.jpg', 'Title 03'],['pics/photo-165.jpg', 'Title 04'],['pics/photo-205.jpg', 'Title 05'],['pics/photo-206.jpg', 'Title 06']];
</script>

You can learn more about JSON here.

We also need to do some small changes in lightbox javascript file so it use our JSON string for image array instead of create array by checking the “rel” attribute in whole page.

You can download the customized lightbox javascript file from here.

You can see the working demo here.

1. Remove the “imageLink” parameter from start function because now we not starting LightBox by not clicking any thumbnail.

start: function(imageLink)

function to

start: function()

2. Now we are initializing the “imageArray” using JSON string.

this.imageArray = [];

to

this.imageArray = img_json;

3. Comment these line of code inside start function bacause we not want to check whole page links for lightbox.

/*if ((imageLink.rel == 'lightbox')){
           // if image is NOT part of a set, add single image to imageArray
           this.imageArray.push([imageLink.href, imageLink.title]);         
  } else {
            // if image is part of a set..
            this.imageArray = 
                $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]').
                collect(function(anchor){ return [anchor.href, anchor.title]; }).
                uniq();
 
            while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; }
  }*/

4. Add function startLightBox() at the end of Lightbox class. This function start the lightbox when we click on the link having id=”start”.

startLightBox: function() {
	var th = this;
	Event.observe($('start'), 'click', function () {
	 	th.start();
	});
}

5. Add this line in initialize() function to call “startLightBox()” function which create the click event on link having id=”start”.

this.startLightBox();

After completing all the five changes in lightbox.js you need to create a link with id = “start” in your HTML file. When you click on this link its starts the LightBox. Here is the code for HTML file.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Initialize LightBox using JSON string and Run it from Flash</title>
<link rel="stylesheet" href="css/lightbox.css" type="text/css" media="screen" />
<script src="js/prototype.js" type="text/javascript"></script>
<script src="js/scriptaculous.js?load=effects,builder" type="text/javascript"></script>
<script src="js/lightbox.js" type="text/javascript"></script>
</head>
<body>
<a href="#" id="start">Start LightBox</a>
</body>
<script language="javascript">
	var img_json = [['pics/photo-80.jpg', 'Title 01'],['pics/photo-128.jpg', 'Title 02'],['pics/photo-160.jpg', 'Title 03'],['pics/photo-165.jpg', 'Title 04'],['pics/photo-205.jpg', 'Title 05'],['pics/photo-206.jpg', 'Title 06']];
</script>
</html>

, , , ,

1 Comment


Create Web Services using AMFPHP and XML-RPC

Here I’m going to demonstrate how we can create web services using AMFPHP and access them using XML-RPC. First, let’s understand some important terms:-

AMFPHP: AMFPHP is a free open-source PHP implementation of the Action Message Format(AMF). AMF allows for binary serialization of Action Script (AS2, AS3) native types and objects to be sent to server side services. You can learn more about AMFPHP from its official website www.amfphp.org.

XML-RPC: It’s a specification and a set of implementations that allow software running on disparate operating systems, running in different environments to make procedure calls over the Internet. You can learn more about AMFPHP from its official website www.xmlrpc.com.

So, here we are creating web services for FLEX or FLASH which we can directly call using the XML-RPC because AMFPHP already included the batteries for XML-RPC and JSON. We don’t need to do any thing special for accessing same services using XML-RPC.

First, we need to download AMFPHP. You can download the latest version of from here.
Unzip the files and place them into your htdocs directory. You can visit http://localhost/amfphp/gateway.php URL in your local to check the AMFPHP is properly installed or not.

1. How to create web service using AMFPHP
In AMFPHP, all files related to web services should be places inside “amfphp\services” directory. I’m considering here an example of “Order” Web Service to make understand it easily.

<?php
/**
 * This class provide methods for handling orders received through web
 */
class WebOrders {
	function _getStoreInfo($storeid) {
		$query_id = mysql_query("SELECT * FROM store WHERE storeid = '$storeid' AND status = 1");
 
		if (!mysql_num_rows($query_id)) {
			return false;
		}
 
		return mysql_fetch_object($query_id);
	}
 
	/**
     * Method to receive new order from web.
     * @returns order request id. In case of error return error message.
     */
    function receiveNewOrder($order) {
		$store_info = $this->_getStoreInfo($order['storeid']);
 
		if (!$store_info) {
			return 'Invalid store ID.';
		}
 
		$sql = "SELECT MAX(fld_order_id) AS fld_order_id FROM tbl_order";
 
		$query_id = mysql_query($sql);
 
		$obj = mysql_fetch_object($query_id);
 
		$next_fld_order_id = 1;
 
		if (!is_null($obj->fld_order_id)) {
			$next_fld_order_id = $obj->fld_order_id + 1;
		}
 
                $sql = "INSERT INTO tbl_order(fld_order_id, fld_total, fld_tax, fld_customer_name, fld_phone, fld_address, 
				fld_email_id, fld_del_status, fld_comment_cust, fld_order_status, fld_request_time, fld_lastupdated)
				VALUES('$next_fld_order_id', '{$order['total']}', '{$order['tax']}', '{$order['customer_name']}', '{$order['phone']}', 
				'{$order['address']}', '{$order['email']}', '{$order['delivery']}', '{$order['note']}', '1', NOW(), NOW())";
		$query_id = mysql_query($sql);
 
		foreach ($order['products'] as $product) {
			$sql = "INSERT INTO tbl_order_detail(fld_order_id, fld_pid, fld_qty, fld_uid, fld_price, fld_lastupdated)
					VALUES('$next_fld_order_id', '{$product['productid']}', '{$product['qty']}', '{$product['unit']}', 
					'{$product['price']}', NOW())";
			$query_id = mysql_query($sql);
		}
 
		return $next_fld_order_id;
    }	
}
?>

Here we have created a class “WebOrders”. It’s having two methods “_getStoreInfo” and “receiveNewOrder”. “_getStoreInfo” is the private method (We can create private method by prefixing ‘_’ before function name). Its means no one can access this method of dervice. “receiveNewOrder” method is for receiving the new order request. Its taking “$order” associative array as paramater and return the new order ID.

2. Access it using XML-RPC
We have create a web Service, now we need to access ir using XML-RPC. We need a XML-RPC library for calling the web service. I’m using this one http://phpxmlrpc.sourceforge.net/#download. You can call the web service like this:-

<?php
  	require_once('lib/xmlrpc.inc');
 
  	$xmlrpc_client = new xmlrpc_client("/amfphp/xmlrpc.php", 'localhost', 80);
  	$xmlrpc_client->setDebug(1); //this will print all the responses as they come back
 
  	$order = new stdClass();
  	$order->storeid = 1;
 
        $order->total = 100.50;
        $order->tax = 10.50;
        $order->customer_name = 'Anil Chauhan';
        $order->email = 'meetanilchauhan@varshyl.com';
        $order->phone = '9810713123';
        $order->address = '24 - Laxmi Nagar, Delhi';
        $order->delivery = '1';
        $order->note = 'Test Note';
 
        $order->products[] = array('productid' => 25, 'qty' => 3, 'unit' => '2', 'price' => 30.00);
 
  	$order = php_xmlrpc_encode($order);
 
  	$xmlrpc_message = new xmlrpcmsg("WebOrders.receiveNewOrder", array($order));
  	$xmlrpc_response = $xmlrpc_client->send($xmlrpc_message);
 
  	if($xmlrpc_response->faultCode() == 0){
  		echo $xmlrpc_response->faultString();
  	}else{
  		echo "Pingback successful";
  	}
?>

Here, first we have included the “xmlrpc.inc” lilbrary. Then we have created the object of xmlrpc_client. We have also enabled the debug option using “$xmlrpc_client->setDebug(1);”. Make sure you switch off the debugging option on your production server.

, ,

4 Comments