Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Wednesday, 25 November 2015

Google new reCaptcha Integrate in PHP

Recently Google has been introduced new reCaptcha API called “Are you a robot?”. They name it “NO CAPTCHA reCAPTCHA”. reCAPTCHA is a free service and It is designed to protect your website from spams and abuse. In this tutorial we are going to show you how to integrate it into your website using PHP.


Before integrating reCaptcha on website we required reCaptch key. Below are steps to get reCaptcha key 

1. Click here to create a Google reCaptcha application.
2. Provide your domain detail http:// or https:// (e.g www.example.com) for website registration

3. After registration you will get 2 keys
  Site key – This will be used in HTML code

 Secret Key - This for communication between your site and Google.

Now we have to write the simple HTML code with Google reCaptcha:
<?php
require_once 'GooglePageRank.php';
$webUrl=$_POST['website_url'];
$objGooglePageRank = new GooglePageRank();
$result =  "$webUrl has Google PageRank:". $objGooglePageRank->get_google_pagerank($webUrl);
?>

index.php:
Contains PHP code, Here we have to modifed Google Secret Key
<?php
    if(isset($_POST['submit'])){
        $captcha=$_POST['g-recaptcha-response'];
        if(!empty($captcha))
        {
            $errMsg= '';
            $google_url="https://www.google.com/recaptcha/api/siteverify";
            $secret=_YOUR_SECRET_KEY;
            $ip=$_SERVER['REMOTE_ADDR'];
            $captchaurl=$google_url."?secret=".$secret."&response=".$captcha."&remoteip=".$ip;
           
            $curl_init = curl_init();
            curl_setopt($curl_init, CURLOPT_URL, $captchaurl);
            curl_setopt($curl_init, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl_init, CURLOPT_TIMEOUT, 10);
            $results = curl_exec($curl_init);
            curl_close($curl_init);
           
            $results= json_decode($results, true);
            if($results['success']){
                $errMsg="Valid reCAPTCHA code. You are human.";
            }else{
                $errMsg="Invalid reCAPTCHA code.";
            }
        }else{
            $errMsg="Please re-enter your reCAPTCHA.";
        }
    }
  
?>

If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.

What is Error and Exception Handling in PHP

Error handling is very important in any programming language. In PHP error level categorized in various kind of error and it’s define all type of error like notice, warning and fatal errors. There are sixteen type of errors level available in PHP. In this tutorial we have mentioned values and constant which can be used in PHP for error reporting using error_reporting() function. 

 

E_ERROR (1) -  It’s a Fatal run-time errors. Execution of the script is stopped.

E_WARNING (2) - It’s a Run-time warnings. Execution of the script is not stopped.

E_PARSE (4) - It’s a compile-time parse error. This errors should only be generated by the parser.

E_NOTICE (8) - It’s a run-time notice indicating that the script encountered something that could possibly an error, however It could also occur when running a script normally.

E_CORE_ERROR (16) - It’s a Fatal errors and occur during PHP’s initial startup.

E_CORE_WARNING (32) - It’s a warning and occur during PHP’s initial startup.

E_COMPILE_ERROR (64) – A fatal error that occur when the script was being compiled.  Except it is generated by the Zend Scripting Engine.

E_COMPILE_WARNING  (128) - A warning (non-fatal error) that occur when the script was being compiled.  Except it is generated by the Zend Scripting Engine.

E_USER_ERROR (256) – It’s user-generated error message like an E_ERROR. It is generated by the PHP code using the function trigger_error().

E_USER_WARNING (512) - It’s user-generated warning message like an E_WARNING. It is generated by the PHP code using the function trigger_error().

E_USER_NOTICE (1024) - A user-generated notice message like an E_NOTICE. It is generated by the PHP code using the function trigger_error().

E_STRICT (2048) - Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.

E_RECOVERABLE_ERROR (4096) - A catchable fatal error. It indicates that a probably dangerous error occurred, but did not leave the Engine in an unstable state.

E_DEPRECATED (8192) – It’s a Run-time notices.

E_USER_DEPRECATED (16384) - User-generated warning message. This is like an E_DEPRECATED.

E_ALL (32767) - All errors and warnings

SOURCE - http://php.net/manual/en/errorfunc.constants.php

Basic Usage of PHP’s error reporting

If you want to hide all type of error , warning of notice then just use error_reporting() as mentioned below:

error_reporting(0);

 
If you want to show all type of error , warning of notice then just use error_reporting() as mentioned below:

error_reporting(E_ALL);

 
Advanced Usage of PHP’s error reporting

If you want to show warnings and errors only then use

error_reporting(E_ERROR | ERROR_WARNING);

 
if you want to show all types but want o hide notices then user
 

error_reporting(E_ALL ^ E_NOTICE);

 

Monday, 23 November 2015

Stripe Payment Gateway Integrate Using PHP

There are lots of payment gateway available in the web market like PayPal, iTransact, Card Gate Plus, SagePay, ANZ eGate and many more. Today, we are going to introduce one of the most powerful payment gateway for Web and Mobile payment. Yes, we are talking about Stripe Payment Gateway.
Integration of Stripe payment gateway using PHP is very easy. Just follow few steps and it will be ready.

Stripe take care the processing and keeping client’s card data so no information of essence would be stored on our server and you would not have to comply with all the rules that come with storing credit/debit cards. 


Step 1: Create an account on Stripe https://dashboard.stripe.com/register. 

Step 2: Login your account and go to Account setting for API Keys.

 

 

Step 3: Download the source code and replace the secret key in payment.php:
<?php
try {  
    require_once('Stripe/lib/Stripe.php');
    Stripe::setApiKey("XXXX_YOUR_SECRET_KEY"); //Replace with your Secret Key  
    $charge = Stripe_Charge::create(array(
                "amount" => 2100,
                "currency" => "usd",
                "card" => $_POST['stripeToken'],
                "description" => "Demo Transaction"
            ));
    //send the file, this line will be reached if no error was thrown above
    echo "<h1>Your payment has been completed.</h1>";
    //you can send the file to this email:
    echo $_POST['stripeEmail'];
}

Step 4: Edit index.php file and replace with your Publishable Key

<script src="https://checkout.stripe.com/checkout.js"
    class="stripe-button"
    data-key="XXX_YOUR_PUBLISHER_KEY" //Replace with your Publishable key
    data-image="http://www.stepblogging.com/wp-content/uploads/2014/12/logo1.png"
    data-name="StepBlogging.com"
    data-description="Demo Transaction ($21.00)"
    data-amount="2100" />
</script>

The test version does not entail any actual funds. However for testing you can use below mentioned detail:
Testing Card Number - 4242424242424242
CVV Number - 1234 
Card Expiry Date - Use any future date

If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.

Google Map API Integrate Using PHP

To display geographic information using Google Map is a very important and demanding feature of website. To integrate Google Map is a difficult task for PHP beginners. In this tutorial we are going to explain how to integrate Google Map API using PHP and display the location on Google Map.

 

 A simple HTML form to capture user address detail:

<html>
<head>
    <meta http-equiv="Content-Type"content="text/html; charset=UTF-8">
    <title>Google Map API  Integrate Using PHP </title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
</head>
<body>
<div class='web'>
    <h1>How To Load Data On Page Scroll Using JQuery</h1> <br />
    <div class='inner'>
        <form class="mapinfo" method="POST" action="index.php">
            <label>Address</label>
            <input type="text" id="address" name="address" />
            </br>
            <label>city</label>
            <input type="text" id="city" name="city" />
            </br>
            <label>state</label>
            <input type="text" id="state" name="state" />
            </br>
            <label>country</label>
            <input type="text" id="country" name="country" />
            </br>
            <label>zip</label>
            <input type="text" id="zip" name="zip" />
            </br>
            <input type="submit" id="submit" name="submit" />
        </form>
    </div>
</div>
</body>
</html>

PHP Code to call google map api and fetch the detail:
<?php
if(isset($_POST['submit'])){
    $address = urlencode($_POST['address']);
    $city = urlencode($_POST['city']);
    $state = urlencode($_POST['state']);
    $country   = urlencode($_POST['country']);
    $zip = $_POST['zip'];
    $resultGeoCode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$address.',+'.$city.',+'.$state.',+'.$country.'&sensor=false');
 
    $output= json_decode($resultGeoCode);
    if($output->status == 'OK'){
        $latitude = $output->results[0]->geometry->location->lat; //Returns Latitude
        $longitude = $output->results[0]->geometry->location->lng; // Returns Longitude
        $location = $output->results[0]->formatted_address;
    }
}
?>

Javascript code to generate map after getting the response from google map api:
<script type="text/javascript">
$(document).ready(function () {
function initialize() {
 
// Define the latitude and longitude positions
var latitude = parseFloat("<?php echo $latitude; ?>"); // Latitude get from above variable
var longitude = parseFloat("<?php echo $longitude; ?>"); // Longitude from same
var latlngPos = new google.maps.LatLng(latitude, longitude);
 
// Set up options for the Google map
var myOptions = {
zoom: 13,
center: latlngPos,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControlOptions: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
}
};
// Define the map
map = new google.maps.Map(document.getElementById("display_map"), myOptions);
 
addMarker(latlngPos, 'Default Marker', map);
  
  google.maps.event.addListener(map, 'dragstart', function(event) {
  //infowindow.open(map,marker);
      addMarker(event.latlngPos, 'Click Generated Marker', map);
  
   var lat, lng, address;
                    
  });
 
  
}
  function addMarker(latlng,title,map) {
    var marker = new google.maps.Marker({
            position: latlng,
            map: map,
            title: title,
icon:'marker.png',
            draggable:true,
animation: google.maps.Animation.DROP
    });
 
    google.maps.event.addListener(marker,'drag',function(event) {
        document.getElementById('lat').value = event.latLng.lat();
        document.getElementById('lng').value= event.latLng.lng();
    });
 
    google.maps.event.addListener(marker,'dragend',function(event) {
        document.getElementById('lat').value = event.latLng.lat();
        document.getElementById('lng').value = event.latLng.lng();
alert(marker.getPosition());
    });
   google.maps.event.addListener(map, 'zoom_changed', function () {
      document.getElementById('zoom').value =map.getZoom();
    });
}
google.maps.event.addDomListener(window, 'load', initialize);
});
</script>

If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.

Friday, 20 November 2015

Google Page Rank Check Using PHP

What is Google Pagerank?
It’s a ranking given by Google to any page (between 0 to 10) which is based on total numbers of backlinks to page. Pagerank is an algorithm to calculate the importance of webpage. In Search engine ranking, Pagerank is an important factor. Higher the pagerank will get higher SERP (search engine results page) position.

In this article, we explain how to get Google page rank for any website using simple PHP class.

index.php:
<?php
require_once 'GooglePageRank.php';
$webUrl=$_POST['website_url'];
$objGooglePageRank = new GooglePageRank();
$result =  "$webUrl has Google PageRank:". $objGooglePageRank->get_google_pagerank($webUrl);
?>

  GooglePageRank.php: (Class File)
<?php
class GooglePageRank{
public function get_google_pagerank($url) {
$query="http://toolbarqueries.google.com/tbr?client=navclient-auto&ch=".$this->CheckHash($this->HashURL($url)). "&features=Rank&q=info:".$url."&num=100&filter=0";
$data=file_get_contents($query);
$pos = strpos($data, "Rank_");
if($pos === false){} else{
$pagerank = substr($data, $pos + 9);
return $pagerank;
}
}
public function StrToNum($Str, $Check, $Magic){
$Int32Unit = 4294967296; // 2^32
$length = strlen($Str);
for ($i = 0; $i < $length; $i++) {
$Check *= $Magic;
if ($Check >= $Int32Unit) {
$Check = ($Check - $Int32Unit * (int) ($Check / $Int32Unit));
$Check = ($Check < -2147483648) ? ($Check + $Int32Unit) : $Check;
}
$Check += ord($Str{$i});
}
return $Check;
}
public function HashURL($String){
$Check1 = $this->StrToNum($String, 0x1505, 0x21);
$Check2 = $this->StrToNum($String, 0, 0x1003F);
$Check1 >>= 2;
$Check1 = (($Check1 >> 4) & 0x3FFFFC0 ) | ($Check1 & 0x3F);
$Check1 = (($Check1 >> 4) & 0x3FFC00 ) | ($Check1 & 0x3FF);
$Check1 = (($Check1 >> 4) & 0x3C000 ) | ($Check1 & 0x3FFF);
$T1 = (((($Check1 & 0x3C0) << 4) | ($Check1 & 0x3C)) <<2 ) | ($Check2 & 0xF0F );
$T2 = (((($Check1 & 0xFFFFC000) << 4) | ($Check1 & 0x3C00)) << 0xA) | ($Check2 & 0xF0F0000 );
return ($T1 | $T2);
}
public function CheckHash($Hashnum){
$CheckByte = 0;
$Flag = 0;
$HashStr = sprintf('%u', $Hashnum) ;
$length = strlen($HashStr);
for ($i = $length - 1; $i >= 0; $i --) {
$Re = $HashStr{$i};
if (1 === ($Flag % 2)) {
$Re += $Re;
$Re = (int)($Re / 10) + ($Re % 10);
}
$CheckByte += $Re;
$Flag ++;
}
$CheckByte %= 10;
if (0 !== $CheckByte) {
$CheckByte = 10 - $CheckByte;
if (1 === ($Flag % 2) ) {
if (1 === ($CheckByte % 2)) {
$CheckByte += 9;
}
$CheckByte >>= 1;
}
}
return '7'.$CheckByte.$HashStr;
}
}
?>

If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.