Getting technorati ranking in PHP without using their API

Today, I was going through the Technorati API to find the rank of the blog using PHP. Those who doesn’t know about Technorati, Technorati is known as the authority for tracking, indexing and ranking the blog sytems. When I went through the Technorati Api, I found that it is not that hard to get the ranking of a blog which is indexed in Technorati.You need to get the developer API  key from Technorati and use their Web Services to get the ranking of a blog.

But, those who are not registered to the Technorati, here is the shortcut method to get the ranking of blogs indexed under Technorati without using their Api. I’ve used the following  URL of technorati

“http://www.technorati.com/blogs/<blog-url>”

and used some regular expression to find the ranking of the blog indexed under technorati withoug using their API.

PHP code to find the technorati ranking without using API

<?php
//enter the blog url don't include http
$blog_url="roshanbh.com.np";
//seeting the URL for technorati
$technorati_url="http://www.technorati.com/blogs/".$blog_url;
//get the html code of the URL
$html_values=file_get_contents($technorati_url);
//get the string within <div></div>
preg_match("@<div\b[^>]* class=\"rank\">(.*?)</div>@si",$html_values,$matches);
//strip out of the HTML element from the matches
$rankvalue=strip_tags($matches[1]);
//geting the the rank values out of the string
preg_match("/(\d+(,\d+)?(,\d+)?)/",$rank_value,$matches);
//Display the rank.
echo "Technorati rank is : ".$matches[0];
?>

Download Source Code

As you can above, I’ve used file_get_contens() function of PHP to get the content from Technorati. The rank of the blog if found under the division “<div class=”rank”></div>” in that page of Technorati, you can verify it by viewing the source of that page. After that, I’ve used few regular expression to find the ranking of the blog in PHP.

One thing you must notice that this code will works under this design of Technorati, if the technorati will change the design then there is no guarantee that this code will work at that scenario.

Getting country , city name from IP address in PHP

Yesterday, miaki asked me how can we get the country name from the IP address in PHP. Today, I’ve come up with the answer of this question. I’ve used the API from hostip.info to fetch the country name , city name and country code from the given IP address. I’ve mad this function in PHP which uses XML response from hostip.info and extracted country name, city name and country code using regular expression.

Function to return country, city name from IP address in PHP

function countryCityFromIP($ipAddr)
{
//function to find country and city from IP address
//Developed by Roshan Bhattarai http://roshanbh.com.np

//verify the IP address for the
ip2long($ipAddr)== -1 || ip2long($ipAddr) === false ? trigger_error("Invalid IP", E_USER_ERROR) : "";
$ipDetail=array(); //initialize a blank array

//get the XML result from hostip.info
$xml = file_get_contents("http://api.hostip.info/?ip=".$ipAddr);

//get the city name inside the node <gml:name> and </gml:name>
preg_match("@<Hostip>(\s)*<gml:name>(.*?)</gml:name>@si",$xml,$match);

//assing the city name to the array
$ipDetail['city']=$match[2]; 

//get the country name inside the node <countryName> and </countryName>
preg_match("@<countryName>(.*?)</countryName>@si",$xml,$matches);

//assign the country name to the $ipDetail array
$ipDetail['country']=$matches[1];

//get the country name inside the node <countryName> and </countryName>
preg_match("@<countryAbbrev>(.*?)</countryAbbrev>@si",$xml,$cc_match);
$ipDetail['country_code']=$cc_match[1]; //assing the country code to array

//return the array containing city, country and country code
return $ipDetail;

}

Download Source Code

As you can see, I’ve documented all the PHP code and I don’t think I need explain anymore about that code. Just notice that, this function returns the array containg three key elements “country” , “city” and “country_code”. Each elements have the value of city, country and country code.

Now, look the the how we can use the above function in PHP,

$IPDetail=countryCityFromIP('12.215.42.19');
echo $IPDetail['country']; //country of that IP address
echo $IPDetail['city']; //outputs the IP detail of the city

Notice that the above PHP function returns the array containing the country , city and country code from IP Address and we can use them in PHP. If you want to know how to get IP address in PHP, you can check this post how you can get real IP address in PHP.

Web Services and PHP – SOAP vs XML-RPC vs REST

What is web services?

In a typical web surfing scenario, a visitor visits a website and use the functionality provided by that particular website.HTTP request is send to server from web browsers and server responses are translated by browser to display the desired result of the visitor. But, this scenario has been changed in the recent days. You don’t need to visit the particular website to use their service and functionality if they are providing web services. Web services are set of platform independent exposed APIs(functions) which can be used used from remote server over the Internet. There are basically two parties involved in this, one which provides a set of exposed APIs and the another one ,commonly know as web services consumers,is the party which uses the functionality and services provided by web services providing party.

There are different method for providing web services but the most common are SOAP, XML-RPC and REST .

SOAP

SOAP was the acronym of Simple Object Access Protocal but this acronym was dropped in the version of 1.2 of SOAP. It is method for exchanging XML based message over the Internet for providing and consuming web services. SOAP message are transferred forming the SOAP-Envelope.You can view the typical SOAP Message articture from here. SOAP is widely criticized for it’s design complexity.

In PHP 5, there is built-in extension for the providing and consuming web services. But, I personally prefer Nusoap toolkit of PHP for providing and consuming web services using SOAP in PHP.

XML-RPC

XML-RPC (remote procedure call) another way of providing and consuming web services. It uses XML to encode and decode the remote procedure call along with it’s parameter. Compared to the articture of SOAP, it has simpler architecture. You can even define data type of parameters of procedure in XML-RPC. You can visit the official website www.xmlrpc.com to know more about XML-RPC.

In PHP, there is extension which contain various functions for facilating XML-RPC request and response. But the functions xmlrpc_encode_request() and xmlrpc_decode_request() available in PHP is very useful for when it comes to encode and decode XML-RPC request and response.

I’ve built  Nepali Currency Converter using XML-RPC web services provided by foxrate.org.

REST

Representational State Trasfer(REST) is comparatively simpler method for providing and consuming web services. Nowadays, this method is becoming popular in the arena of web services. Unlike above two method, it is not necessary to use XML as a data interchange format in REST. REST architecture is basically focused on two things : Resources and Interface.RESTful  is another term to define REST web services .

Resources are application’s state and functionality which is represented by a unique URL. The resources share a uniform interface to transfer the state between the client and server.

For example the URL, http://example.com/product/11 can be a resource.Suppose, GET method is used to retrieve product detail from that URL, POST method is used to modify the production information and DELETE method can be used to delete the product from the same URL. Here, the HTTP methods works as a interface to access the resources.

Talking about PHP, the format of information(representation) returned can be in XML, JSON or even in HTML format. DOM functions, SimpleXML functions and JSON functions comes handy when you are handling RESTful interfaces in PHP.

How to filter user submitted data easily in PHP?

Yesterday, I saw one of my friend was working on the the contact form and was filtering the user input data(posted variables) individually. He was using a function in PHP to filter the input and using  tedious approach while calling the filtering function for each variables with coding  each of them in single line . Today, I’m going to show you how can you filter the posted variables easily using callback function in PHP.

PHP function to filter the user supplied data.

function filter_data($val)
{
  return htmlentities($val,ENT_QUOTES);
}

This is just a example of very simple function is PHP to filter the user ssubmitted data.But ,you can add more code according to your requirement to make this function robust.

Common programmer’s approach to filter submitted data in PHP

$name=filter_data($_POST['name']);
$email=filter_data($_POST['email']);
$website=filter_data($_POST['website']);

It was the approach which I’ve used in beginning of my career and most of the beginner PHP programmer use this approach to filter the posted variables.And, the above list can be long if there are more posted data.At that time, it will be very irritating to use the same kind of line in many places.

Using array_map() function to filter the posted data in PHP

As you know, POST variables are super global array in PHP and you can use array_map() function in PHP to filter the input using the callback function. Let’s see how you can filter the the posted data easily,

$post=array_map("filter_data",$_POST);

As you can, each values of POST variables is mapped into another array using a call back function filter_data() which is defined above.

Now, you can access the filtered variables easilly with $post['name'] or $post['email'] etc.

Handling array of HTML Form Elements in JavaScript and PHP

Today, I would like to share the way of handling array of HTML FORM elements using JavaScript and PHP.Well, it’s very easy to get the data from the array of HTML form elements in PHP and using them but in JavaScript it’s a bit tricky to handle the array of HTML form elements. I had a hard time to handle them via JavaScript in past thats why I’m posting it here so that people will not have hard time to cope with array of form elements in JavaScript and PHP.

Array of HTML form elements

You can create the array of Form Elements for grouping the similar kind of object or data. The array of elements are very useful in the context where you don’t know how many similar kind of data user have to enter. For example, you have a form where user have to enter his education qualification then you might not know how many of the textboxes are required for a person and in such kind situation you can dynamically generate array of the elements in the form for entering such kind of information.

<input name="education[]" type="text" size="20" maxlength="40" />
<input name="education[]" type="text" size="20" maxlength="40" />
<input name="education[]" type="text" size="20" maxlength="40" />

As you can in the above code, there are array element of textbox defined with the name “education”.Now, let’s see how can we handle them via JavaScript and PHP.

How to handle array of HTML form elements using PHP

If you submit the the the form with the above the array of elements then you can assess it via array of $_POST['education'] in PHP. You can use foreach() loop to access the value of the value of these form elements via PHP.

foreach($_POST['education'] as $key=>$value)
 echo $key.' '.$value;

Normally, posted variable are contained within the POST array but when you post the array of Form Elements then at that time the values are contained within the array of array i.e within $_POST['education'] in above exmaple.

How to handle array of Form elements using JavaScript

Handling the array of Form element part is a bit tricky. Now, let try to access the values of the above elements using JavaScript. First, let’s store the above object in a JavaScript variable

var mutli_education = document.form_name.elements["education[]"];

After storing the object in the variable, we can access the individual variables in the following way in JavaScript

for(i=0;i<mutli_education.length;i++)
{
 alert(mutli_education[i].value);
}

As you can see, you can get how many elements are there in the array using the lengh property and you can use the value property to get the value of the indivisual element.

Get free ebooks of essential PHP and JavaScript tips , tricks & Hacks

As you might know that this blog and tradepub.com are providing free magazines to the reader of this blog. You can check the free magazines and E-book in the free magazines resource of this blog. You can find a collection of great resources of IT knowledge from here. And, today I’m here to highlight the great E-books from sitepoint.com on essential PHP and JavaScript tips , tricks  and other resources.

Free E-book on the essential tips, tricks and hacks of JavaScript and PHP

You can find the great list of resources for the web developer in the list below. You can check them out grab a copy of your E-book right now.

  • The PHP Anthology: 101 Essential Tips, Tricks & Hacks, 2nd Edition – Free 207 Page Preview!
  • The JavaScript Anthology: 101 Essential Tips, Tricks & Hacks – Free 158 Page Preview

Other resources which are be very useful for the web developer. Do check them out and get a copy of yours.

  • The Principles Of Project Management – Free 66 Page Preview!
  • The ASP.NET 2.0 Anthology: 101 Essential Tips, Tricks & Hacks – Free 156 Page Preview
  • Run Your Own Web Server Using Linux & Apache – Free 191 Page Preview
  • Remote Replication Best Practices for Oracle 10g using XP Continuous Access
  • Best Practices for Implementing HP Quality Center Software

Force download multiple files in a zip archive using PHP

In this post, I’ll show you how can you download the multiples files in a zip archive using PHP. I’ve made a function in PHP where you’ve to pass the parameters the array of files to be zipped, the second parameter is file name as which zip archive file has to be downloaded and finally the path of files where files to be zipped are located.(assuming that they are all in same folder)

PHP function to download mutiple files in a zip archive

//function to zip and force download the files using PHP
function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
  //create the object
  $zip = new ZipArchive();
  //create the file and throw the error if unsuccessful
  if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
    exit("cannot open <$archive_file_name>\n");
  }

  //add each files of $file_name array to archive
  foreach($file_names as $files)
  {
    $zip->addFile($file_path.$files,$files);
  }
  $zip->close();

  //then send the headers to foce download the zip file
  header("Content-type: application/zip");
  header("Content-Disposition: attachment; filename=$archive_file_name");
  header("Pragma: no-cache");
  header("Expires: 0");
  readfile("$archive_file_name");
  exit;
}

Download Source code

In the above PHP function, first of all the object of ZipArchive class. Remember that this library is bundled in PHP after the version of PHP 5.2 only.If you’re using the PHP version older than that one then you’ve to get it from PECL extension.

After that, we’ve tried to create the zip arhive with the open() function using the ZIPARCHIVE::CREATE flag.After successfully creating the archive, each files whose names are passed as array are added to zip file using addFile() function of ZipArchive() class.Then, this zip archive is closed using close() function of same class.

And, finally different headers are passed through PHP to force download the newly created zip file.

Example of Using Above PHP function

  $file_names=array('test.php','test1.txt');
  $archive_file_name='zipped.zip';
  $file_path=dirname(__FILE__).'/';
  zipFilesAndDownload($file_names,$archive_file_name,$file_path);

The above PHP function call is straighforward and after calling that function you’ll get the zip archive containing mutiple files passed as array in the first parameter of the function.

Changing textbox value from dropdown list using Ajax and PHP

Yesterday Tarquin macey asked me how can we change the value of the textbox based using Ajax and PHP based on the changing value of the dropdown list.Today, I’ve come up with a solution from him.In this post, you’ll see how to get the currency code of a country from PHP using Ajax and this currency code will replace the value of textbox each time the dropdown list changes.

Writing Code for changing textbox value from dropdown list using Ajax and PHP

After looking at the above demo, let’s start writing code for the changing the currency code value in the textbox form Ajax using PHP when you changes the country from the dropdown list.

HTML Code

<select name="country" onChange="getCurrencyCode('find_ccode.php?country='+this.value)">
 <option value="">Select Country</option>
        <option value="1">USA</option>
        <option value="2">UK</option>
        <option value="3">Nepal</option>
</select>
<input type="text" name="cur_code" id="cur_code" >

As you can in the above code, there are two main components one dropdown list whose name is country and contains the list country in it.The JavaScript function getCurrencyCode() is called when user change value in the list. Note down the name and id of textbox which will have the currency code fetched from Ajax.

JavaScript Code for changing textbox value without refreshing the page

function getCurrencyCode(strURL)
{
  var req = getXMLHTTP();
  if (req)
  {
        //function to be called when state is changed
        req.onreadystatechange = function()
        {
          //when state is completed i.e 4
          if (req.readyState == 4)
          {
                // only if http status is "OK"
                if (req.status == 200)
                {
                        document.getElementById('cur_code').value=req.responseText;
                }
                else
                {
                        alert("There was a problem while using XMLHTTP:\n" + req.statusText);
                }
          }
        }
        req.open("GET", strURL, true);
        req.send(null);
  }
}

In the first line of the above code, the XMLHTTPRequest object is created using getXMLHTTP() function. To look at the the structure of this function, take a look at this old post change the value of dropdown list using Ajax and PHP . After checking the appropriate value of readystate(4 means completed) and status(200 means ok) property of XMLHTTPRequest object, the value of textbox is replaced with the returned value from PHP using Ajax . The response ,which is can be accessed via req.responseText property, is written to textbox via the value property of textbox.

PHP code for changing the value of textbox using Ajax and PHP

<?php
$country=$_REQUEST['country'];
switch($country)
{
        case "1" :
                echo "USD";
                break;
        case "2" :
                echo "GBP";
                break;
        case "3" :
                echo "NPR";
                break;
}
?>

As you can see the above PHP code, it is fairly simple which just print the currency code value according to the name of country. The value which is in the echo statement is going to returned from PHP via Ajax.

Download Full Source Code

Solving Floating point number precision lost problem in PHP

The problem of precision lost in floating point number in PHP haunted me for about 10 minutes yesterday but I quickly figured out the problem and solved it as I was aware of this problem. But, I would like to post here it here so that many others PHP programmers, who are not aware with this kind of problem ,get solution easily and don’t get stuck with it.

Calculation problem floating Point number in PHP

First of all, let me show you a small piece of example of the PHP code which I was working on.

$no_of_time=(0.60-0.55)*100;
var_dump($no_of_time); //displays float(5)
for($i=1;$i<=$no_of_time;$i++)
{
   echo $i;
}

In the above code,  the line var_dump($no_of_time); displays float(5). Ok, this is a expected result. But what about the loop, which runs just for 4 time. The above loop runs just for four time although var_dump () outputs that it is 5. Yes, it is 5 but with lost precision and that why never ever trust on the regular arithematic calculation with the floating point numbers in PHP. It always gives the wrong result because of the problem of lost precision. You can also see this warning in the PHP’s website.

Solving the problem of floating point precision in PHP

To solve this problem in floating point number, you need the function which calculates and support the calculation of floating point number of any precision. And, I recommend you to use BC Math functions, the binary calculator, of PHP for calculations  of floating point number to prevent yourself from the problem of precision lost. But note down that, these functions always returns calculated output as string.Now, let’s try to solve the problem of above code rewrite it using bcsub and bcmul functions of PHP.

$no_of_time=bcmul(bcsub(0.60,0.55,2),100);
var_dump($no_of_time); //display string(1) "5"
for($i=1;$i<=$no_of_time;$i++)
{
   echo $i;
}

Now the above, loop runs 5 times without any problem.

Solving European characters (Western charset) problem with Ajax and PHP

Today, I would like to tell you how to handle character set problem which occurs during the data fetched from PHP using Ajax mainly on the western characters(European charset).Lots of people asked me about this problem where these European charset is displayed in unreadable format after fetching it from ajax.

Problem with European Charset with Ajax and PHP

Suppose that I’ve the following code in PHP file, which output the string which contain the european characters.

<?php
  $str="€-accentuée";
  echo $str;
?>

Now, let’s use the Ajax from JavaScript using Jquery Code to fetch the data from PHP.

<script type="text/javascript">
$(function()
{
  $('#charsetdiv').load("test2.php");
});
</script>
<div id="charsetdiv"></div>

If you’ve not used jQuery then you might be wondering about the ajax code, you can check the benefits of jquery from this post and download free ebook of jQuery.

After getting value from Ajax, the division with id “charsetdiv”, let’s look at the output.

?-accentu?e

Solving western Character Set problem with Ajax and PHP

The above problem is occurred because of not defining proper charset to these European characters. We can solve this problem by sending the header which define the appropriate Character Set for these characters.Let’s see, how I solve this problem just adding the header which define the charset Windows-1256 – which support Arabic as well as European characters.

<?php
  header("Content-Type: text/html; charset=Windows-1256\n");
  $str="€-accentuée";
  echo $str;
?>

After adding that header in PHP, you’ll get the appropriate european characters in your Ajax enabled application.

Powered by WordPress | iCellPhoneDeals.com Offers Free Wireless Deals. | Thanks to Bestincellphones.com Verizon Cell Phones, Best CD Rates Online and Fat Burning Furnace Review