Friday 14 December 2012

Creating Marker / Overlays in Google Map

Overlays in Google maps are used to point to a specific location that we point to. It is an easy task. Here in this tutorial I'm only stressing at creating Overlays , if any doubt regarding creating maps please refer to my previous post.

So lets get started.
Overlays are objects on the map that are bound to latitude/longitude coordinates.Google maps has several types of overlays: Marker, Polyline, Polygon, Circle, Rectangle etc.

Google Maps - Add a Marker

Add the marker to the map by using the setMap() method:
See demo

<script>

var myCenter=new google.maps.LatLng(9.9667,76.2167);

function initialize()

{

var mapProp = {

  center:myCenter,

  zoom:5,

  mapTypeId:google.maps.MapTypeId.ROADMAP

  };



var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);



//Marker

var marker=new google.maps.Marker({

  position:myCenter,

});

marker.setMap(map);

}

//End

google.maps.event.addDomListener(window, 'load', initialize);

</script>


Animating Marker

Applying animation property to the marker.
See demo

marker=new google.maps.Marker({

  position:myCenter,

  animation:google.maps.Animation.BOUNCE

  });

marker.setMap(map);




Thank You!

Creating Google Maps using API

Creating a Basic Google Map

Here we going to discuss about creating Google maps with API. API means 'Application Program Interface'. Before proceeding to the tutorial for the maps to work an API key is needed which can be received free of cost from Google.

In this section I will explain you how to create a basic Google Map. Its easy, just try it out...,
See demo

<!DOCTYPE html>

<html>

<head>

<script src="http://maps.googleapis.com/maps/api/js?key=<YOUR_API_KEY>&sensor=false">

</script>



<script>

function initialize()

{

var mapProp = {

  center:new google.maps.LatLng(9.9667,76.2167),

  zoom:5,

  mapTypeId:google.maps.MapTypeId.ROADMAP

  };

var map=new google.maps.Map(document.getElementById("googleMap")

  ,mapProp);

}



google.maps.event.addDomListener(window, 'load', initialize);

</script>

</head>



<body>

<div id="googleMap" style="width:500px;height:380px;"></div>



</body>

</html>


Code Explanation 

<script src="http://maps.googleapis.com/maps/api/js?key=<YOUR_API_KEY>&sensor=false">
</script>
This tag is required to include Google Maps API. key=<YOUR_API_KEY> , enter you API key provided.
The "sensor" attribute can be true or false.

var mapProp = {

      center:new google.maps.LatLng(9.9667,76.2167),

      zoom:5,

      mapTypeId:google.maps.MapTypeId.ROADMAP

  };

"center" property decides were to center the map depending upon the latitude and longitude given.
"zoom" decides the initial zoom level of the map.
"mapTypeId" property specifies the map type. It can be ROADMAP, HYBRID, TERRAIN and so on..,

Finally on execution the map will be shown on the specified target.

Its all about creating a basic Google Map. If any suggestions or help please use the comments area.

Thank You!




Friday 7 December 2012

Creating RSS Feed in PHP

Do you know what is RSS feed?
RSS is a great way to promote your blog. In fact, most blogs will automatically set up an RSS feed to go with the blog unless you specifically tell the software not to. It is not only for blog, you might have heard about podcasts, but you can also promote other articles, new products or just interesting information with an RSS feed.

Some interesting uses of RSS feeds that I've seen include:

  • What's new with the company or website.
  • Lists of just about anything - from gift wishlists to rental queues to quotations and more.
  • Daily quotes or subscription details. etc.
RSS feeds provide an easy, almost automated way to update your site's content. It allows viewers the opportunity to decide what they want to read without forcing them to go anywhere, which they`re likely to appreciate. It allows both human readers and search engine spiders to find content based on keywords without compromising the quality for either one. It`s an excellent way to market any type of website, but especially blogs since these tend to be updated much more frequently and consequently have more subscribers. It`s a great method for keeping people informed during a collaborative effort. Having your feed taken up by other webmasters can increase the number and quality of back-links to your site.

Well, lets come to our topic Creating RSS feed with PHP.

feed-xml.php

'feed-xml.php' is a feed for your website, make sure the below script is edited upon your requirement.
<?php
    header("Content-Type: application/rss+xml; charset=ISO-8859-1");
    DEFINE ('DB_USER', 'root');   
    DEFINE ('DB_PASSWORD', '');   
    DEFINE ('DB_HOST', 'localhost');   
    DEFINE ('DB_NAME', 'codersbay'); 
    $rssfeed = '<?xml version="1.0" encoding="ISO-8859-1"?>';
    $rssfeed .= '<rss version="2.0">';
    $rssfeed .= '<channel>';
    $rssfeed .= '<title>NFPM</title>';
    $rssfeed .= '<link>Link to the Site</link>';
    $rssfeed .= '<description>Descirption about your site.</description>';
    $rssfeed .= '<language>en-us</language>';
    $rssfeed .= '<copyright>Copyright (C) 2012 glen-online.webege.com</copyright>';
    $connection = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)
        or die('Could not connect to database');
    mysql_select_db(DB_NAME)
        or die ('Could not select database');
    $query = "SELECT * FROM blog ORDER BY date DESC";
    $result = mysql_query($query) or die ("Could not execute query");
    while($row = mysql_fetch_array($result)) {
        extract($row);
 
        $rssfeed .= '<item>';
        $rssfeed .= '<title>' . $row['title'] . '</title>';
        $rssfeed .= '<description>' . $row['contents'] . '</description>';
        //$rssfeed .= '<link>' . $link . '</link>';
        $rssfeed .= '<pubDate>' . date("D, d M Y H:i:s O", strtotime($row['date'])) . '</pubDate>';
        $rssfeed .= '</item>';
    }
    $rssfeed .= '</channel>';
    $rssfeed .= '</rss>';
    echo $rssfeed;
?>

On your web page add this script to show feed burner icon and to call the above functionality.

<a href="javascript:(function(){var a=window,b=document,c=encodeURIComponent,d=a.open('http://www.seocentro.com/cgi-bin/promotion/bookmark-rss/rss.pl?u='+c( 'http://your-site/feed-xml.php' ),'bookmark_popup','left='+((a.screenX||a.screenLeft)+10)+',top='+((a.screenY||a.screenTop)+10)+',height=480px,width=720px,scrollbars=1,resizable=1,alwaysRaised=1');a.setTimeout(function(){ d.focus()},300)})();" title="RSS" class="rss">
<img src='http://www.businessawardseurope.com/images/general/rss75x75.gif' alt='rss' />
</a>

Check it out, if any suggestions or doubts please use the comment facility.

Thank You!.

Tuesday 4 December 2012

HTML to PDF Conversion in PHP

Today I'm presenting you one interesting feature in PHP, it is nothing but html to pdf conversion just using a simple php scripts. For this purpose we will be using a 3rd party library which can make our job easy.

The third party library I'm introducing is "HTML2PDF". For creating a pdf out of html file please refer below:

test.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Test HTML</title>
</head>

<body>
<h1>HTML TO PDF</h1>
    <p>Hello World!</p>
</body>
</html>

Above is a html snippet. Here it is a demo to convert the above html file to pdf. See the code below.


index.php


<?php
error_reporting(0);
require("html2fpdf.php");          

$htmlFile = "test.html";
$buffer = file_get_contents($htmlFile);

$pdf = new HTML2FPDF('P', 'mm', 'Letter');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('test.pdf', 'F');
?>

"html2fpdf.php" included is the library. Click here to download.

It the simplest method available to convert html to pdf. Please suggest any idea if you find any.

Thank You!

Monday 3 December 2012

Unzipping a zipped file using PHP


Below is a code to unzip a zipped file. Hope you can make the best of it.

function.php

<?php
    function unzip($ziplocation,$unzippedLocation){
        if(exec("unzip $ziplocation",$arr)){
            mkdir($newLocation);
            for($i = 1;$i< count($arr);$i++){
                $file = trim(preg_replace("~inflating: ~","",$arr[$i]));
                copy($ziplocation.'/'.$file,$unzippedLocation.'/'.$file);
                unlink($ziplocation.'/'.$file);
            }
            return TRUE;
        }else{
            return FALSE;
        }
    }
?>

index.php


<?php
include 'functions.php';
if(unzip('zipfolder/test.zip','unziped/newZip'))
    echo 'Success!';
else
    echo 'Error';
?>

Thank You!

Email validation in PHP


Email validation in php using regular expression.

$email = $_POST['email'];
if(preg_match("~([a-zA-Z0-9!#$%&amp;'*+-/=?^_`{|}~])@([a-zA-Z0-9-]).([a-zA-Z0-9]{2,4})~",$email)) {
    echo 'This is a valid email.';
} else{
    echo 'This is an invalid email.';
}

Thank You!

Sunday 2 December 2012

Payment through WorldPay

WorldPay is one of the well known payment gateways available. Here it an integration code. Hope you will find it helpful.

<html>
<!-- The name, style, and properties of the page are defined in the 'head' tags. -->
<head>
<title>HTML Redirect Example 0.1</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Junior HTML Example 0.1">
<meta name="keywords" content="Junior, html">
<style type="text/css">td {text-align:"left"; vertical-align:"middle"; font-family:"arial"; color:"black"} h1,h2,h3,h4,h5,h6,h7 {text-align:"center"; vertical-align:"middle"; font-family:"arial"; color:"black"}</style>
</head>

<!-- The content to be used on the page is placed between the 'body' tags. -->
<body>

<!-- This is a purchase token, for more information on the elements with in a purchase token see the supplied help section. -->
<form action="https://secure-test.worldpay.com/wcc/purchase" name="BuyForm" method="POST">
<input type="hidden" name="instId"  value="211616">
<input type="hidden" name="cartId" value="abc123">
<input type="hidden" name="currency" value="GBP">
<input type="hidden" name="amount"  value="0">
<input type="hidden" name="desc" value="">
<input type="hidden" name="testMode" value="100">

<!-- JavaScript is used to give functionality to some of the pages elements. -->
<script language=JavaScript>

<!-- This function defines the price of each product. To add the product edit further down the page. -->
function calc(productNo)
{
if (productNo==1)
{
document.BuyForm.amount.value = 5.00;
document.BuyForm.desc.value = "Product 1";
}
else if (productNo==2)
{
document.BuyForm.amount.value = 10.00;
document.BuyForm.desc.value = "Product 2";
}
<!-- To add a new product price, copy from here... -->
else if (productNo==3)
{
document.BuyForm.amount.value = 15.00;
document.BuyForm.desc.value = "Product 3";
}
<!-- ...to here, and paste directly below. You will need to alter the 'productNo' and its price value. -->
}

</script>

<h1>One-Click Shop</h1>

<!-- This table provides layout for the products listed on the webpage. -->
<table align="center" cellpadding="3" border="2">
<tr>
<td>Product 1</td>
<td> Price: &pound;5.00</td>
<td><input type="image" src="buy_button.jpg" alt="Buy button" onClick="calc(1)"></td>
</tr>
<tr>
<td>Product 2</td>
<td>Price: &pound;10.00</td>
<td><input type="image" src="buy_button.jpg" alt="Buy button" onClick="calc(2)"></td>
</tr>
<!-- To add a new product, copy from here... -->
<tr>
<td>Product 3</td>
<td>Price: &pound;15.00</td>
<td><input type="image" src="buy_button.jpg" alt="Buy button" onClick="calc(3)"></td>
</tr>
<!-- ...to here, and paste directly below. You will need to alter three things: the product number, price, and calc(put product number here) -->
</table>

</form>
</body>
</html>

Thank You!

Saturday 1 December 2012

Image Upload in Different Sizes in PHP

Below is a PHP code to upload image in different sizes. This code will be useful while creating image gallery, shopping carts or any other colorful web based projects.

index.php

<!-- html code [UI] -->


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>File Upload</title>
</head>

<body>
<form method="post" enctype="multipart/form-data">
    <p>
        <input type="file" name="file" id="file" />
            <input type="submit" name="submit" id="submit" value="Upload" />
        </p>
    </form>
</body>
</html>
<!-- html end -->

<!-- image upload and processing code in php -->


<?php
define ("MAX_SIZE","500");

$errors=0;

if($_SERVER["REQUEST_METHOD"] == "POST")
{
$image =$_FILES["file"]["name"];
$uploadedfile = $_FILES['file']['tmp_name'];

if ($image)
{
$filename = stripslashes($_FILES['file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
echo ' Unknown Image extension ';
$errors=1;
}
else
{
$size=filesize($_FILES['file']['tmp_name']);

if ($size > MAX_SIZE*1024)
{
echo "You have exceeded the size limit";
$errors=1;
}

if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}

list($width,$height)=getimagesize($uploadedfile);

$newwidth=800;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);

$newwidth1=75;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,
$width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,
$width,$height);

$filename = "uploads/". $_FILES['file']['name'];
$filename1 = "uploads/small". $_FILES['file']['name'];

imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);

imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}
}
}
//If no errors registred, print the success message

if(isset($_POST['Submit']) && !$errors)
{
// mysql_query("update SQL statement ");
echo "Image Uploaded Successfully!";
}

function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
?>


<!-- End -->

Here using the above code the image will be uploaded in two different sizes with width's 800px & 75px respectively.

Thank You!

Importing Excel Records to MySQL

How to import MS Excel records to as MySQL table?

At first before executing the below query the Excel document should converted to .csv format. For this select save as and chose file type as *.csv(Comma delimiter).

The query is as follows:

LOAD DATA LOCAL INFILE '[path://]file.csv' INTO TABLE database.tableName FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' (field1,field2,field3,.....);

Thank You!