Archive for category Web Service

Create a TinyURL using PHP and TinyURL API

TinyURL is an awesome service. For those who don’t know what TinyURL is, TinyURL allows you to convert your long URLs like “http://www.akchauhan.com/category/jquery/” to small URLs like “http://tinyurl.com/yz4c4ba”. Basically you need such type of service when you are posting your data to some third party web service and there is limit on the number of characters you can post like Twitter. Twitter only allow 140 characters long Tweet.

Using the PHP and TinyURL API, you can create these tiny URLs.

function get_tiny_url($url)  
{  
	$ch = curl_init();  
	$timeout = 5;  
	curl_setopt($ch,CURLOPT_URL,'http://tinyurl.com/api-create.php?url='.$url);  
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);  
	curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);  
	$data = curl_exec($ch);  
	curl_close($ch);  
 
	return $data;  
}
 
//test it out!
$new_url = get_tiny_url('http://www.akchauhan.com/category/jquery/');
 
//returns http://tinyurl.com/yz4c4ba
echo $new_url;

,

6 Comments


Create Windows Service to Schedule PHP Script execution

If you want to schedule your PHP script or any other command on Windows Platform recursively after a fix interval of time then you can create a Windows Service for it. Windows service is very easy to create in Visual Studio.Net. I’m using C# language for this scheduler service you can also use VB.net for it. Basically we need this type of service if we want to execute some PHP script in background in a specific interval of time. For example, If you want to import data in bulk from some web service.

You need to follow these steps: -

  • Create a project by using the Windows Service application template. This template creates a class for you that inherits from ServiceBase and writes much of the basic service code, such as the code to start the service.
  • Write the code for the OnStart and OnStop procedures, and override any other methods that you want to redefine.
  • Add the necessary installers for your service application. By default, a class that contains two or more installers is added to your application when you click the Add Installer link: one to install the process, and one for each associated service that your project contains.
  • Build your project.
  • Create a setup project to install your service, and then install it.
  • Access the Windows 2000 Services Control Manager and start your service.

For more detail check “Walkthrough: Creating a Windows Service Application in the Component Designer” topic in MSDN.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
 
namespace MyNewService
{
    public partial class MyNewService : ServiceBase
    {
        private Timer syncTimer = null;  
 
        public MyNewService()
        {
            InitializeComponent();
        }
 
        protected override void OnStart(string[] args)
        {
            syncTimer = new Timer();
            this.syncTimer.Interval = 180000;
            this.syncTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.syncTimer_Tick);
            syncTimer.Enabled = true;
        }
 
        protected override void OnStop()
        {
            syncTimer.Enabled = false;
        }
 
        private void syncTimer_Tick(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(@"C:\xampp\htdocs\task.bat");
        }  
    }
}

The task.bat file is a batch file. We are executing our PHP script through this batch file. First we set the path of directory where php.exe is located in your windows. The import.php is basically importing data in bulk from some web and we need to execute this script file background in every 3 minutes.

@echo off
cd\
set path=C:\xampp\php;
cd "C:\xampp\htdocs"
php import.php
exit

, , ,

2 Comments


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.

, ,

1 Comment