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!

Friday 30 November 2012

Create thumbnails for Youtube & Vimeo Videos using PHP

Here we are going to see how to generate thumbnail images from youtube and vimeo videos. This article will be useful when creating a video gallery.

Creating thumbnails of Youtube videos

Creating thumbnails for Youtube is an easy task to perform, actually PHP code is not necessary to perform this.

Each YouTube video has 4 generated images. They are predictably formatted as follows:

http://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg
http://img.youtube.com/vi/<insert-youtube-video-id-here>/1.jpg
http://img.youtube.com/vi/<insert-youtube-video-id-here>/2.jpg
http://img.youtube.com/vi/<insert-youtube-video-id-here>/3.jpg

Example:
Say link "http://www.youtube.com/watch?v=QdoTdG_VNV4&feature=g-all",
In this youtube link video id is "QdoTdG_VNV4". So if you want to create thumbnail for this videos use this id with the above representation.

http://img.youtube.com/vi/QdoTdG_VNV/0.jpg

Creating thumbnails of Vimeo videos

For Vimeo thumbnails can be generated using simple PHP code. 

<?php

$imgid = <video-id>;

$hash = unserialize(file_get_contents("http://vimeo.com/api/v2/video/$imgid.php"));

echo $hash[0]['thumbnail_medium'];  

?>

If "http://vimeo.com/36519586" is the Vimeo link then <video-id> is "36519586".


Thank You!

Thursday 29 November 2012

Creating 404 page in PHP (.htaccess)

404 is a status shown by your browser when the requested page is not found by your server. In PHP you can design a custom 404 page using .htaccess functionality. Here is a sample code for this:

.htaccess
RewriteEngine on
ErrorDocument 404 [path]404.php

Place this code in your projects root. 404.php can be a custom page designed by you. Try it out.

Thank You!

Wednesday 28 November 2012

Download Link Using PHP


Create a download link using PHP.

It needs two files index.php and download.php, this is just for an representation. Below is the code:

index.php
<a href="download.php?file=conent.zip" title="Download">
       <b>Download file</b>
</a>

download.php

<?php
$file =$_GET['file'];
header("Content-type: application/text");
header("Content-Disposition: attachment; filename=". $file);
readfile($file);
?>

Tuesday 27 November 2012

Print Current Day to End Day of Month in PHP


<?php
$datetime_start = strtotime(date('D Y/m/d'));
$datetime_end   = strtotime(date("D Y/m/d",mktime(0, 0, 0, (date('m') + 1), 0, date('Y'))));

$datetime_temp = $datetime_start;
?>

<select class="input-box" name="">
<?php while ($datetime_temp <= $datetime_end) { ?>
<option><?php echo date('D d/m/Y', $datetime_temp); ?></option>
<?php
$datetime_temp = strtotime('+1 day', $datetime_temp);  
}
?>
</select>

Fetch data from database using php

Fetching Data From Database,

There is mainly two function that can be used to fetch data in php
1. mysql_fetch_array()   : Returns values as arrays.
2. mysql_fetch_object() : Return object
<?php
     $select = "select * from <table_name>";
     $result = mysql_query($select);
?>

1. mysql_fetch_array() 
<?php
   $data=mysql_fetch_array($result);
   $optionField1 = $data['fieldname1'];
   $optionField2 = $data['fieldname2'];
?>

2. mysql_fetch_object()

<?php
   $data=mysql_fetch_object($result);
   $optionField1 = $data->fieldname1;
   $optionField2 = $data->fieldname2;
?>

Thank You!

Monday 26 November 2012

Php code to update values in database

Lets see how we can use php mysql to update values in the database,

Database connection and other related facts are discussed earlier, so let move on to update directly,

Syntax: update <table_name> set <field1>='[update value]' where [condition 1][condition 2]....

See this demo,

id   |  name
1       Rogg
2       Hoggs
3       Brad

In the above that we need to update the name 'Hoggs' with 'Hopes',

<?php
     $update = "update test_table set name='Hopes' where id=2";
     $result   = mysql_query($update);
?>

The statement will result in updation of the record with id is '2'.

Thank You.

Sunday 25 November 2012

Php code to insert values into database

Here it is a sample code to insert elements into database.

Inserting elements into database is a simple task, but before performing this task we should be connected with database and so on.

How to get connected with database using php?

Here in this case with are opting MySQL as the database, world's largest open source database. Connection is like this:

         $con=mysql_connect('[Host]','[username]','[password]') or die ('Connection failed');
         Format is like this.

<?php
        $con=mysql_connect('localhost','root','') or die ('Connection failed');
?>

This will connect you to the database, if not it will prompt you an error message 'Connection failed'. And our task is to insert data on to database.

<?php
        mysql_connect_db('db_name',$con) or die('Connection to database failed');
                                                                //Set database connection.
                                                                //Say 'db_name' as database name.
?>

Insert values to database:

<?php
      $sql_insert="insert into <table_name> values (field1,field2) values ('val1','val2')";
      $result      =mysql_query($sql_insert);
?>

Thank You!


Create Your Own Social Media Buttons

Here are the scripts to create Social Media Buttons. These include Facebook like button, Tweet button & Google's 1+ button.


Google +

<html>
<head>
        <title>+1 demo: Basic page</title>
        <link rel=”canonical” href=”http://www.example.com” />
       <script type=”text/javascript” src=”https://apis.google.com/js/plusone.js”></script>
</head>
<body>
 <g:plusone></g:plusone> or <g:plusone size='medium' count='true' href='YOUR LINK TO +1' ></g:plusone>
</body>
</html>


Facebook

1, <fb:like send="false" href="http://glen-online.webege.com" layout="standard" width="80" show_faces="false" action="like" colorscheme="light"></fb:like>

<div id="fb-root"></div>
<script>
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>

2, IFrame version

   <iframe src="http://www.facebook.com/antony.g.pinheiro" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:450px; height:px">

Twitter

1, Tweet icon

<div style="position: relative; width: 835px; margin: 0px auto;"><div style="position: absolute; width: 15px; margin: 0 auto; margin-left: 545px; top: 35px; z-index: 999;">
   <a href="http://twitter.com/#!/Mima_Design"><img src="http://twitter-badges.s3.amazonaws.com/t_mini-c.png" alt="Follow Mima_Design on Twitter"></a>
</div></div>