Complete PHP CURL, JSON and Google Maps API Example

Aim
The aim of this tutorial to show how you can combine, CURL, JSON and the Google Map API to create a widget that displays your browser position (internet connection) on a map. This tutorial can also be used as a Google Maps API tutorial, an intorduction to JSON and a php CURL example. This will teach you how to integrate curl, json and the google maps API. We will make a json call to a php script. The script will then open a cURL connection to a service and get your IP information and respond. The json response will then be decoded and displayed on a google map. View this Example at work

Assumptions
This tutorial assumes that you have a php capable web server hosted externally on the internet. If not then you can use the php that is hosted on codediaries. http://codediaries.com/myphp/remoteInfo.php?json=mycallback

Versions used in this example
Sofware/ComponentImage
PHP 5N/A
Apache 2.2N/A
Google Maps API V2N/A
Links to these files can be found here

This example consists of the three files listed below.
Example
_|_requestInfo.js
_|_requestInfo.php
_|_test.html

Open cURL connection and get the IP Information
  • Create the php file
     1. <?php
     2. $xman=$_GET["json"];
     3.  
     4. $ch = curl_init();
     5. curl_setopt($ch, CURLOPT_URL, "http://api.ipinfodb.com/v2/ip_query.php?".
     6. "key=e8418e1d22fe3b8198f3b07728c8e31851d5202b08b5b10c148a2b54dbbdfe1d".
     7. "&timezone=false&ip=".$_SERVER['REMOTE_ADDR']);
     8. 
     9. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    10. 
    11. $output=curl_exec($ch);
    12. 
    13. preg_match("/<CountryName>(.*?)<\/CountryName>/ims",$output, $matches);
    14. $country = $matches[1];
    15. preg_match("/<RegionName>(.*?)<\/RegionName>/ims",$output, $matches);
    16. $region = $matches[1];
    17. preg_match("/<City>(.*?)<\/City>/ims",$output, $matches);
    18. $city= $matches[1];
    19. preg_match("/<Latitude>(.*?)<\/Latitude>/ims",$output, $matches);
    20. $lat= $matches[1];
    21. preg_match("/<Longitude>(.*?)<\/Longitude>/ims",$output, $matches);
    22. $long= $matches[1];
    23.   
    24. $jsonstring = "{\"user_agent\":\"".urlencode($_SERVER['HTTP_USER_AGENT'])."\",";
    25. $jsonstring.= "\"ip\":\"".urlencode($_SERVER['REMOTE_ADDR'])."\",";
    26. $jsonstring.= "\"country\":\"".urlencode($country)."\",";
    27. $jsonstring.= "\"region\":\"".urlencode($region)."\",";
    28. $jsonstring.= "\"city\":\"".urlencode($city)."\",";
    29. $jsonstring.= "\"lat\":\"".urlencode($lat)."\",";
    30. $jsonstring.= "\"lng\":\"".urlencode($long)."\",";
    31. $jsonstring.= "\"referer\":\"".urlencode($_SERVER['HTTP_REFERRER'])."\"}";
    32. 
    33. header("Content-Type: text/javascript");
    34. echo $xman."(".$jsonstring.");";
    35. ?>
    Hide line numbers
    What is being passed to the php script in the $_GET['json'] parameter is the name of the javascript function.

    Line 5 you call ipinfo.com with the IP obtained from $_SERVER['remote_addr']. This returns an XML file. You need to register at their site and get an API key for your use.

    Lines 13-22 Decode the xml file to extract the country, region, city

    Lines 24-31 Create the json response from the details

    Lines 33-34 Set the header as javascript and return the information with the original function name you received at line 2.
    `
  • Now host this file in your php enabled server. For this example to work the file has to be hosted on an external server. If you host it locally, the remote_addr attribute will give you 127.0.0.1 which is meaningless. If you do not have an external host then you can use http://codediaries.com/myphp/remoteInfo.php
    `
  • Test the script by calling it with json=mycallback in your browser.
    http://codediaries.com/myphp/remoteInfo.php?json=mycallback
    You should see som text in your browser. The json format is given below.

    mycallback(
    {"user_agent":"Mozilla Firefox ...",
    "country":"Australia",
    "region":"New South Wales",
    "lat":"908833",
    "long":"33346",
    ......
    "referer":""
    }

    )
The Google Maps Javascipt
  • This is the remoteInfo.js file.
     1. var map;
     2. function initialize(lat, lng) {
     3.     var myOptions = {
     4.         zoom: 2,
     5.         center: new google.maps.LatLng(lat, lng),
     6.         mapTypeId: google.maps.MapTypeId.ROADMAP
     7.     }
     8.     map = new google.maps.Map(document.getElementById("map_canvas"),
     9.                                   myOptions);
    10. }
    11. function markMe(lat, lng, text){
    12.     var image = 'http://google-maps-icons.googlecode.com/files/friends.png';
    13.     var myLatLng = new google.maps.LatLng(lat, lng);
    14.     var beachMarker = new google.maps.Marker({
    15.         position: myLatLng,
    16.         map: map,
    17.         icon: image
    18.     });
    19.     infowindow = new google.maps.InfoWindow({content : text});
    20.     google.maps.event.addListener(beachMarker, "click", function() {
    21.         infowindow.open(map, beachMarker);    
    22.     });
    23. }
    24. function urldecode(x){
    25.     return unescape(x).replace(/\+/g," ");
    26. }
    27. function mycback(resp){
    28.     initialize(resp.lat, resp.lng);
    29.     text=urldecode(resp.ip)+"<br/>"+urldecode(resp.country)+"<br/>"+urldecode(resp.region)+"<br/>"+urldecode(resp.city);
    30.     markMe(resp.lat, resp.lng, text);
    31. }
    32. document.write("<script type=\"text/javascript\" src=\"http://codediaries.com/myphp/remoteInfo.php?json=mycback\"/>");
    Hide line numbers

    Line 32 Calls the previous php script with json=mycback. Once this get's called when it returns javascript like below.
    mycback({"userr-agent":"mozilla",.....,"referer":""})
    This then calls mycback on Line 27. Note that you should point this url to where you hosted your remoteInfo.php file.

    Line 27 mycback has access to all the json response values in the form of resp.lat, resp.user_agent etc. It then calls Initialize() to initialize the map and then markMe(), to place a marker on the map

Putting it all together
  • This is the html file that calls the js file. This is saved as test.html
     1. <html>
     2. <head>
     3. </head>
     4. <body>
     5. <div id="map_canvas" style="width:295px;height:250px;font-family:arial;font-size:0.75em"></div>
     6. <script type="text/javascript" src="http://maps.google.com/maps/api/js?key=ABQIAAAAU34fqM8XohIf42U76GcxNhQD6263AO_J-cN-o5MVlTXsf8kbcBRgf8XZKHTaVeqWfZVYZJ5ub5dW3A&sensor=false"></script>  
     7. <script type="text/javascript" src="remoteInfo.js"></script> 
     8. <script type="text/javascript">
     9. /**Dummy**/
    10. </script> 
    11. </body>
    12. </html>
    Hide line numbers

    Line 5 Has the 'div' with id='map_canvas'. Google will create the map in this layer.

    Line 6 This loads the API. Note, you will need an API key for this. You can use the one in the example, but you should get one of your own. You can get one at Google Maps.

    Line 7 You are including the remoteInfo.js file from the previous section. The remoteInfo.js and test.html file are in the same directory for this example.

    Lines 8-10 Is a little trick you need to include to make it work. Just add it.
    `
  • Now opent remoteInfo.html and you should see your position displayed on a map.

Example of Browsing Location Widget

Find out where you are browsing from, using this widget. Get your IP, Country, Region and area information from this widget.




Learn more about this widget
A widget that displays the location details of your internet connection on a map. This uses, PHP cURL, JSON and Google maps API to create a new mashup

Creating a PHP Web Proxy Server - Part 1

Aim
This tutorial aims to create a web proxy server from scratch. It is split into 5 sections. A web proxy does not require any configuration settings such as proxy ip and port on your browser. Whereas conventional proxy servers found on corporate firwalls require these settings. Basically a web proxy is a web-application such as a php script that receives a request, creates a new connection to the requested resource, gets the data and then sends the data back to the client.

Assumptions.
While coding such a proxy is fairly straightforward, the complexity comes from HTML and the HTTP protocol itself. You will need basic php skills, some basic regular expression skills and a rudinentary understaning of html and http.

Versions used in this example
Sofware/Component
Image
Apache 2.2
N/A
php 5.2.1.2
N/A
Links to these files can be found here

How does a php web based proxy work? The proxy is actually a php application/web page.
1. Accept a url from a webpage (get request)
2. Open a cURL connection to the url you received.
3. Read the html.
4. Replace all the links in the html file to point to your php application
5. Return the output to the client.

  • As an example, let us assume that a user wishes to connect to a page at http://mysite.com/out.html. The contents of the file are given below.
     1. <html>
     2. <head>
     3.   <link rel="stylesheet" type="text/css" 
     4.     href="mystyle.css"/>
     5.   <script type="text/javascript" 
     6.     src="http://codediaries.com/jslib/ads.js"></script>
     7. </head>
     8. <body>
     9.   <h1>PHP Proxy</h1>
    10.   This is a test page to show
    11.   what a php web-page proxy does.
    12.   <br/>
    13.   You can find more information at 
    14.   <a href="http://codediaries.blogspot.com">Code diaries</a>
    15.   <br/>
    16.   <a href="help.html">Help</a> | 
    17.   <a href="contact.html">Contact</a>
    18. </body>
    19. </html>
    Hide line numbers

  • Let us also assume that the php proxy is hosted at http://127.0.0.1/php/proxy.php. So you give it the url you want to view, like below (in your browser).
    http://127.0.0.1/php/proxy.php?urlP=http://mysite.com/out.html

  • Your proxy.php then recieves the url and opens up a cURL connection to the host and downloads the page.

  • Then you use regular expressions or some other method to change all the urls to point to your proxy. The urls are usually base64 encoded to make them 'safe'
     1. <html>
     2. <head>
     3.   <link rel="stylesheet" type="text/css" 
     4.     href="http://127.0.0.1/php/prxprod/proxy?urlE=aHR0cDovLzEyNy4wLjAuMS9waHAvYi9teXN0eWxlLmNzcw__"/>
     5.   <script type="text/javascript" 
     6.     src="http://127.0.0.1/php/prxprod/proxy?urlE=aHR0cDovL2NvZGVkaWFyaWVzLmNvbS9qc2xpYi9hZHMuanM_"></script>
     7. </head>
     8. <body>
     9.   <h1>PHP Proxy</h1>
    10.   This is a test page to show
    11.   what a php web-page proxy does.
    12.   <br/>
    13.   You can find more information at 
    14.   <a href="http://127.0.0.1/php/prxprod/proxy?urlE=aHR0cDovL2NvZGVkaWFyaWVzLmJsb2dzcG90LmNvbQ__">Code diaries</a>
    15. 
    16.   <br/>
    17.   <a href="http://127.0.0.1/php/prxprod/proxy?urlE=aHR0cDovLzEyNy4wLjAuMS9waHAvYi9oZWxwLmh0bWw_">Help</a> | 
    18.   <a href="http://127.0.0.1/php/prxprod/proxy?urlE=aHR0cDovLzEyNy4wLjAuMS9waHAvYi9jb250YWN0Lmh0bWw_">Contact</a>
    19. </body>
    20. </html>
    Hide line numbers

    As you will notice all the urls have been replaced by something like
    http://127.0.0.1/php/prxprod/proxy?urlE=aHR0cDovLzEyNy4wLjAuMS9waHAvYi9teXN0eWxlLmNzcw__
    The string after the urlE actually contains the fully qualified url. If we look at line 4, the aHR0cDo... strin contains http://mysite.com/mysite.css encoded in base 64.

  • Now send this changed output back to the requesting browser.

  • Now when your script receives a request such as the one below,
    http://127.0.0.1/php/prxprod/proxy?urlE=aHR0cDovLzEyNy4wLjAuMS9waHAvYi9teXN0eWxlLmNzcw__
    You will have to base64 decode the string and make a cURL request to the site.


As you can see by rewriting all the urls, all requests for css and js files go through your proxy. Also, all links will now go via your proxy too.

In the next part we will look at the base cURL proxy skeleton to get us started.