Showing posts with label API. Show all posts
Showing posts with label API. Show all posts

Paytm Payment Gateway Integration in PHP - Example

On 1/22/2018 Be the first to comment!

Hi! In this tutorial, we will see how to integrate paytm payment gateway in php. Mobile wallets have become immensely popular in recent years and paytm is highly trusted among online customers. Many people use it every day for doing online recharges, DTH & other bill payments. It reduces the risk of exposing customer's banking credentials and credit card details to hackers. Therefore, Paytm is a good solution for online payments on your Website and Mobile Apps.

Integrating the paytm gateway in your application is quite easy and below I'll show how to do it with php.

paytm payment gateway integration php

Paytm Payment Gateway PHP Integration:

If your application is based on php, then you don't have to go from scratch. You can quickly integrate paytm into the application using the paytm kit for php. It covers all the basics, you just have to download and use it in the following way.

Step-1) Download Paytm Kit

Download Paytm Payment Kit for PHP and extract its contents. Then move the 'PaytmKit' folder to your working directory.

Step-2) Register for Paytm Sandbox Account

Next, you must register for merchant sandbox account with paytm and collect the necessary details to use with the API. Visit this link and provide your mobile number, email id and password and register an account. You will be provided with merchant id, key etc. Store them in a text file to use it later.

Step-3) Configure the Settings

Now you must configure the payment gateway settings with the data you received in Step-2. Open 'PaytmKit' > 'lib' > 'config_paytm.php' file and update the following details.

define('PAYTM_ENVIRONMENT', 'TEST'); //change this to 'PROD' to use it in production environment
define('PAYTM_MERCHANT_KEY', 'YOUR_MERCHANT_KEY'); //Change this to the merchant key downloaded from the portal
define('PAYTM_MERCHANT_MID', 'YOUR_MERCHANT_ID'); //change this to merchant id received from paytm
define('PAYTM_MERCHANT_WEBSITE', 'WEBSITE_NAME'); //change this to website name received from paytm

Step-4) Create Payment Form

Finally create a payment form to make transactions. Here we need to pass the form action to file 'pgRedirect.php' located inside the 'PaytmKit' folder. This will take care of verifying the checksum and other details and process the payment via the paytm wallet.

<!doctype html>
<html>
<head>
<title>PHP Patym Gateway Integration Demo</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div class="container">
    <div class="col-xs-6 col-xs-offset-3">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="text-center">Paytm Payment Gateway Demo</h3>
            </div>
            <div class="panel-body">
            <form action="pgRedirect.php" method="post">
                <div class="form-group">
                    <input type="text" class="form-control" id="ORDER_ID" name="ORDER_ID" size="20" maxlength="20" autocomplete="off" tabindex="1" value="<?php echo  "ORDS" . rand(10000,99999999)?>">
                </div>
                <div class="form-group">
                    <input type="text" class="form-control" id="CUST_ID" name="CUST_ID" maxlength="12" size="12" autocomplete="off" tabindex="2" value="CUST001">
                </div>
                <div class="form-group">
                    <input type="text" class="form-control" id="INDUSTRY_TYPE_ID" name="INDUSTRY_TYPE_ID" maxlength="12" size="12"  autocomplete="off" tabindex="3" value="Retail">
                </div>
                <div class="form-group">
                    <input type="text" class="form-control" id="CHANNEL_ID" name="CHANNEL_ID" maxlength="12" size="12" autocomplete="off" tabindex="4" value="WEB">
                </div>
                <div class="form-group">
                    <input type="text" class="form-control" id="TXN_AMOUNT" name="TXN_AMOUNT" autocomplete="off" tabindex="5" value="1">
                </div>
                <div class="form-group">
                    <input type="submit" name="submit" value="CheckOut" class="btn btn-success btn-lg">
                </div>
            </form>
            </div>
        </div>
    </div>
</div>
</body>
</html>

This is just a usual php form, but remember to pass all the required parameters as I did. And for designing UI, I have used bootstrap css here, but you can happily skip it if you don't want.

php paytm payment demo

You can refer the official documentation for more details about Paytm gateway API.

Read Also:

That explains about paytm payment gateway integration in php. Using the kit really simplifies the task and allows you quickly add the paytm payment option to your web/mobile applications. I hope you like this tutorial. Please share it on social media if you find it useful.

How to Get Country Name from IP Address with PHP

On 1/15/2018 Be the first to comment!

Hi! In this post, let's see how to get country name from ip address using php. When working on multilingual web applications, it is mandatory to find the geographic location of the visitors, so that you can provide the contents that match the specific location. Some websites even change country flags and themes accordingly.

With PHP, you can get the visitor's IP easily, but unfortunately there's no way to get the country details from it. Hence, you have to rely on external web services to provide the location details. Here I'm going to show you how to find the country of visitors with the help of GeoPlugin API and PHP.

php get country name from ip address

Getting Country Name from IP Address with GeoPlugin:

GeoPlugin is a free web service that provides geographical location of site visitors from IP. It offers various types of services like PHP, JSON etc., and in this tutorial, I'm going to use the JSON API to find the country name.

You have to access the service with this url,

http://www.geoplugin.net/json.gp?ip=IP_ADDRESS

The API will return the name of the country along with other details related to the location, such as city, currency, latitude, longitude, etc.

Below I have created a PHP function getIP(). It accepts the IP Address as a parameter, communicates with the geoPlugin api and returns the country name for that IP.

PHP Function:

<?php
function getIP($ipadr) {
    if(isset($ipadr)) {
        $details = file_get_contents('http://www.geoplugin.net/json.gp?ip=' . $ipadr);
        $json = json_decode($details);
        if($json->geoplugin_status == '200')
            return $json->geoplugin_countryName;
        else
            return 'Error getting country name.';
    } else {
        return 'IP is empty.';
    }
}
?>

Usage:

You must call the function like this,

<?php
echo getIP('17.142.180.78');

// output
// United States 
?>

What the function does is, take the ip address and send the http request to the api using file_get_contents() method. The api returns the json response, which it decodes with json_decode(), parses for the country name and returns it.

Finding Visitor Country Location:

In case you want to find the visitor's location, you must pass the client ip address to the function in this way,

<?php echo getIP($_SERVER['REMOTE_ADDR']); ?>

Keep in mind to use this on live server, because REMOTE_ADDR will return the default ip '127.0.0.1' when you run it from localhost.

Read Also:

That explains about getting country name from IP address using geoplugin api and php. The good thing about this API is you do not need to register or obtain an API key to use the web service. It's totally free and simple to use. I hope you like this. Please share this on social networks if you find it useful.

Get JSON from URL in PHP

On 1/09/2018 8 Comments so far

In this tutorial, I’m going to show you how to get json from url in php script. JSON has become a popular way to exchange data and web services outputs in json format. To send a HTTP request and parse JSON response from URL is fairly simple in php but newbies may find how to parse json difficult.

Let's see how to build a php json parser script. For this script, I’m going to access Google MAP web service via API and get latitude and longitude co-ordinates for a location. Google map api produces both json/xml output. But for this example I’m going to get the json response and show you how to parse json object to retrieve the geo-metric details.

php-get-json-from-url

Get Zipcode From Address using PHP and Google Maps API

On 1/05/2018 Be the first to comment!

Hi! We were seeing about Google Maps API for a while, and today's post is also one on the line. In this tutorial, we are going to see how to get zipcode from address using php and google maps api. Sometimes you might have a large set of customers addresses without postal codes. In such cases you can rely on Google maps to provide the pin code you need. It serves queries related to addresses with less effort. So with the help of Google Maps Geocoding API you can easily extract the zip code from the address and I'm going to show you how to do it in php.

get zipcode from address php and google maps api

PHP - Get Zipcode from Address using Google Maps API:

Retrieving zipcode/pincode from the address is a two step process. First we have to get the latitude and longitude for the given address and then use them to get the zip code details.

The API offers two different types of services, geocoding and reverse geocoding of addresses and we have to use both to achieve the desired result.

This is the web service url we have to use,

http://maps.google.com/maps/api/geocode/json

With this, you have to attach the appropriate query parameters to the api url. The result will be returned as JSON.

Let's get started!

Step-1) Getting Latitude & Longitude from Address

<?php
$geocode = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address");
$json = json_decode($geocode);
$latitude = $json->results[0]->geometry->location->lat;
$longitude = $json->results[0]->geometry->location->lng;
?>

Step-2) Getting Zipcode using Latitude, Longitude

<?php
$geocode = file_get_contents("http://maps.google.com/maps/api/geocode/json?latlng=$latitude,$longitude");
$json = json_decode($geocode);

foreach($json->results[0]->address_components as $adr_node) {
    if($adr_node->types[0] == 'postal_code') {
        return $adr_node->long_name;
    }
}
?>

The following is the complete php function to retrieve zip code details from the provided address.

PHP Function:

<?php
function getZipcode($address)
{
    // get geocode
    $geocode = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address");
    $json = json_decode($geocode);
    $latitude = $json->results[0]->geometry->location->lat;
    $longitude = $json->results[0]->geometry->location->lng;
    
    // get zipcode
    $geocode = file_get_contents("http://maps.google.com/maps/api/geocode/json?latlng=$latitude,$longitude");
    $json = json_decode($geocode);
    
    foreach($json->results[0]->address_components as $adr_node) {
        if($adr_node->types[0] == 'postal_code') {
            return $adr_node->long_name;
        }
    }
    return false;
}
?>

The function getZipcode() takes up a single parameter $address and extracts postal_code from the provided address using geocode api.

Usage:

You have to call the above function like this in php.

<?php
// set address
$address = 'Brooklyn, NY, USA';
$address = str_replace(' ', '+', $address);
$zipcode = getZipcode($address);

if($zipcode)
    echo 'Zipcode: ' . $zipcode;
else
    echo 'Zipcode not found! Please try different address!!!';

// output
// Zipcode: 11216
?>

What the above function does is, it takes the address info and request Google API for its geocoding details. Receive the response, decodes the json string and extract the latitude and longitude values from it.

Next, request the API once again by passing the extracted geocoding values, but this time for address details with postal code. This step is called reverse geocoding. It again decodes the json response, iterate over to fetch and return the zipcode.

API Key:

Google imposes request limits per day for using the api. Therefore getting the api_key is the best way for uninterrupted work. Login to your Google account, get the api key and use it in the url like this,

https://maps.googleapis.com/maps/api/geocode/json?address=ADDRESS&key=YOUR_API_KEY

http://maps.google.com/maps/api/geocode/json?latlng=$latitude,$longitude&key=API_KEY;
Read Also:

That was all about fetching zipcode from address in php and google maps api. Although the process seems handful at first, it is really simple once you get to know it. I recommend you to use the api_key parameter with the url, since you can easily exceed the daily limit. I hope you like this post. Appreciate if you share it in your social circle.

Get Address from Latitude and Longitude using PHP and Google Maps API

On 12/14/2017 Be the first to comment!

Hi! Today let's see how to get address from latitude and longitude using PHP and Google Maps Geocoding API. In general, the process of converting geometric coordinates such as latitude and longitude into address is called reverse geocoding. And the geocoding is just the opposite, converting address into latitude and longitude which we have seen in our previous tutorial. Google Maps provides a separate Geocoding API for the purpose and let's see how to use it with php.

To obtain physical addresses from the API, you have to send http request along with latitude and longitude values.

php get address from latitude longitude google maps api

Getting Address from Latitude and Longitude using Google Maps:

To access Google Maps Geocoding API, you need an http interface through which you can send and receive an http request/response from the api. Here is the sample request you should send to the web service.

http://maps.google.com/maps/api/geocode/json?latlng=40.6781784,-73.9441579

The 'latlng' parameter must be used to provide latitude, longitude values in the url. Also, to get the response as json, you must be specific on your api call.

Below is the reverse geocoding sample response that we get for the above api request,

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "58",
               "short_name" : "58",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "Brooklyn Avenue",
               "short_name" : "Brooklyn Ave",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Crown Heights",
               "short_name" : "Crown Heights",
               "types" : [ "neighborhood", "political" ]
            },
            {
               "long_name" : "Brooklyn",
               "short_name" : "Brooklyn",
               "types" : [ "political", "sublocality", "sublocality_level_1" ]
            },
            {
               "long_name" : "Kings County",
               "short_name" : "Kings County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "New York",
               "short_name" : "NY",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "11216",
               "short_name" : "11216",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "58 Brooklyn Ave, Brooklyn, NY 11216, USA",
         "geometry" : {
            "location" : {
               "lat" : 40.677978,
               "lng" : -73.94438700000001
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 40.67932698029149,
                  "lng" : -73.94303801970851
               },
               "southwest" : {
                  "lat" : 40.6766290197085,
                  "lng" : -73.94573598029152
               }
            }
         },
         "place_id" : "ChIJaVKlrIVbwokRhqlQjSdxUHc",
         "types" : [ "street_address" ]
      },
      
      ...
      ...
   ],
   "status" : "OK"
}

The response sends a status flag which you can test to determine the success or failure of the conversion process.

PHP Function to Convert Latitude and Longitude into Address:

Below is the php function to get the address details of the given geographic co-ordinates. You must pass longitude and latitude to the function which in turn makes http request to the api, receive json response, parse and return the formatted address.

<?php
function getAddress($latitude, $longitude)
{
        //google map api url
        $url = "http://maps.google.com/maps/api/geocode/json?latlng=$latitude,$longitude";

        // send http request
        $geocode = file_get_contents($url);
        $json = json_decode($geocode);
        $address = $json->results[0]->formatted_address;
        return $address;
}
?>

Usage:

You have to access the above getAddress() function like this,

<?php
// coordinates
$latitude = '40.6781784';
$longitude = '-73.9441579';
$result = getAddress($latitude, $longitude);
echo 'Address: ' . $result;

// produces output
// Address: 58 Brooklyn Ave, Brooklyn, NY 11216, USA
?>

The php script will output the location as a human-readable address.

API Key:

Without API Key, you're requests credits per day will be very limited. In order to use the API key in each of your requests, you must first activate the Google Maps API and obtain the authentication credentials for it.

Log in to your Google account, go to the API console, activate the 'Google Maps Geocoding API' and get an 'API_KEY'.

Then you can use this key in the url every time you send a request to the api in this way,

http://maps.google.com/maps/api/geocode/json?latlng=$latitude,$longitude&key=API_KEY;

Please note that the sensor param is deprecated in the latest versions of the API. Therefore, it is no longer necessary to attach it with the request URL.

Read Also:

That explains about getting location from latitude and longitude in php using Google Maps Geocoding API. You can use this address info to place a marker on Google Maps. I hope you like this tutorial. If you find this post useful, please share it in your social circle.

Get Latitude and Longitude from Address using PHP and Google Maps API

On 12/12/2017 Be the first to comment!

Hi! In this tutorial, let's see how to get latitude and longitude from address using google maps geocoding api and php. Geocoding is the process of converting physical addresses into geographical coordinates such as latitude and longitude so you can use them to create markers in Google Map. It is also better to provide latitude and longitude when using Google Map API so that you can point to accurate position on the map. To obtain the geocode, we must send an http request to the Google Map Geocoding API along with the formatted address.

php get latitude longitude from address google maps api

How to Get Latitude and Longitude from Address?

The Google Maps Geocoding API is a web service used to obtain geocoding and reverse geocoding of the addresses. And you have to access the api through the HTTP interface.

Here is the sample request you have to send to Geocoding API to get latitude and longitude coordinates.

The API provides a response in both json and xml format. Since json is cross platform compatible, let us inform the api to send the response as json.

// api request
http://maps.google.com/maps/api/geocode/json?address=Brooklyn,+NY,+USA

And the above http request will provide a json response that looks something like this,

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Brooklyn",
               "short_name" : "Brooklyn",
               "types" : [ "political", "sublocality", "sublocality_level_1" ]
            },
            {
               "long_name" : "Kings County",
               "short_name" : "Kings County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "New York",
               "short_name" : "NY",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Brooklyn, NY, USA",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 40.739446,
                  "lng" : -73.83336509999999
               },
               "southwest" : {
                  "lat" : 40.551042,
                  "lng" : -74.05663
               }
            },
            "location" : {
               "lat" : 40.6781784,
               "lng" : -73.94415789999999
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 40.739446,
                  "lng" : -73.83336509999999
               },
               "southwest" : {
                  "lat" : 40.551042,
                  "lng" : -74.05663
               }
            }
         },
         "place_id" : "ChIJCSF8lBZEwokRhngABHRcdoI",
         "types" : [ "political", "sublocality", "sublocality_level_1" ]
      }
   ],
   "status" : "OK"
}

Now let's see how to use this geocoding api in php to get latitude and longitude details of an address.

PHP Function to Get Geocoding from Google Maps:

Here is the php function to get geocoding information. The function takes up address of a location, sends an http request to the google map api, decodes the json response and extracts and returns the coordinates of latitude and longitude.

<?php
function getGeoCode($address)
{
        // geocoding api url
        $url = "http://maps.google.com/maps/api/geocode/json?address=$address";
        // send api request
        $geocode = file_get_contents($url);
        $json = json_decode($geocode);
        $data['lat'] = $json->results[0]->geometry->location->lat;
        $data['lng'] = $json->results[0]->geometry->location->lng;
        return $data;
}
?>

Function Usage:

You have to call the getGeoCode() function like below.

<?php
$address = 'Brooklyn, NY, USA';
$address = str_replace(' ', '+', $address);
$result = getGeoCode($address);
echo 'Latitude: ' . $result['lat'] . ', Longitude: ' . $result['lng'];

// produces output
// Latitude: 40.6781784, Longitude: -73.9441579
?>

Please note that the address you specify must be an actual one and should be formatted by replacing the space character with the '+' operator.

Using API Key:

To use the API key, you must log in to your Google account, activate the 'Google Maps Geocoding API' on your account and get an 'API_KEY'.

Then you can include your key using the key parameter on each request like this,

https://maps.googleapis.com/maps/api/geocode/json?address=FORMATTED_ADDRESS&key=YOUR_API_KEY

The earlier versions of the API, includes sensor parameter to determine if your application uses sensor to find the user's location or not. The parameter is deprecated and no longer necessary with the API call.

Read Also:

That explains about getting latitude and longitude coordinates from a physical address in php using Google Maps Geocoding API. Once you get the geocode, you can use them to position the map. I hope you like this tutorial. If you find it useful, please share the post on your social circle.

Create 3D Pie Charts with JavaScript and Google Charts API

On 11/30/2017 Be the first to comment!

Google Charts API provides you with ready-made charts which you can generate with few lines of java script code. I'll show you here how easy it is to Create 3D Pie Charts with JavaScript and Google Charts API. For this chart tutorial we are going to use Google's Visualization API which is based on pure HTML5/SVH technology, so you don't need extra plug-ins. The pie chart we generate is an interactive chart, which means the user is allowed to interact with them by triggering events like mouse over, clicking, zooming, panning and much more (depends upon the charts we use).

create 3D pie charts with javascript google charts api

This method is relatively simple and does not require any complex server side scripts like PHP or any Databases. Using java script we will make callback to the Google Visualization API with the data set we want to render as a pie chart. The charts will be generated at the time of presentation. So if you want to generate charts from database tables, you can simply make it by querying the data from the DB tables and pass it to the Google API with an AJAX call.

Create 3D Pie Charts with Javascript and Google Charts API

For this Google Charts API example, Let me create a chart showing the user's various social media engagement.

Recommended Read: How to upload files in php securely

First let's include the required Google chart library.

<script type="text/javascript" src="https://www.google.com/jsapi"></script>

Next load the google visualization api with the load() function.

google.load("visualization", "1", {packages:["corechart"]});
  1. The first parameter visualization tells to load the google visualization api.
  2. The second parameter 1 instructs to load the current version of api.
  3. The third parameter {packages:["corechart"]} is an array of visualizations we want to use.

Next we have to set callback to make sure the visualization library is completely loaded.

google.setOnLoadCallback(drawPieChart);

The drawPieChart is the java script function where we'll set up the data and options to be actually rendered as a graph.

function drawPieChart() {
    var data = google.visualization.arrayToDataTable([
        ['Platform','Reach'],
        ['Facebook',13],
        ['Twitter',8],
        ['Google Plus',10],
        ['Linkedin',7],
        ['Tumblr',4],
        ['Pinterest',5]
    ]);

    var options = {
        title: 'Social Media Engagement',
        width: 900,
        height: 500,
        colors: ['#4060A5', '1EC7FE', '#e64522', '#0097BD', '#3a5876', '#cb2027'],
        is3D: true
    };
    var chart = new google.visualization.PieChart(document.getElementById('piechart'));
    chart.draw(data, options);
}

As you can see in the above example, I have set the data table and the options. The options hold the general settings of the chart like the title, the dimensions (width and height) etc. Since I have created a pie chart about various social media reach in the above example, it's only meaningful to set the background colors of those corresponding slices with their brand colors. If it is not set, they will be generated with the default color theme. So I have defined the colors array to generate the chart like I would prefer.

To make the pie chart 3D I have used,

is3D: true

By default this property would be false. You can leave it if you don't want a 3D chart.

Finally used the draw() function to generate the actual graph.

Also in the line,

var chart = new google.visualization.PieChart(document.getElementById('piechart'));

you can see there is a DOM reference to the html element with id piechart which is the actual place holder for our 3D Pie Chart.

<div id="piechart"></div>

Here is the completed code for creating 3d pie charts with javascript and google charts api.

<html>
    <head>
        <title>Create 3D Pie Charts with JavaSript and Google Charts API</title>
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript">
        google.load("visualization", "1", {packages:["corechart"]});
        google.setOnLoadCallback(drawPieChart);
        function drawPieChart() {
            var data = google.visualization.arrayToDataTable([
                ['Platform','Reach'],
                ['Facebook',13],
                ['Twitter',8],
                ['Google Plus',10],
                ['Linkedin',7],
                ['Tumblr',4],
                ['Pinterest',5]
            ]);

            var options = {
                title: 'Social Media Engagement',
                width: 900,
                height: 500,
                colors: ['#4060A5', '1EC7FE', '#e64522', '#0097BD', '#3a5876', '#cb2027'],
                is3D: true
            };
            var chart = new google.visualization.PieChart(document.getElementById('piechart'));
            chart.draw(data, options);
        }
        </script>
    </head>
    <body>
        <div id="piechart"></div>
    </body>
</html>

Now run it in the browser and you can see a beautiful 3d pie chart generated.

As I've already said it's an interactive chart, hover the mouse over the pie slices and you can see a nice tooltip appears mentioning the given name and shared percentage of the slice.

Recommended Read: How to get the Status Code from HTTP Response Headers in PHP

Over to you

Do you like this 3D pie charts using java script tutorial? Then what are you waiting for? Go ahead and power up your site's user experience with Google Charts API. Not to mention I would appreciate your kindness to share it your social media circle :)

Take Webpage Screenshot using PHP and PageSpeed Insights API

On 10/09/2017 Be the first to comment!

Hi! Today I have come up with an interesting post which is about taking screenshot of webpage using PHP and Google PageSpeed Insights API. This handy feature will help you provide thumbnail preview of websites to improve user experience on your sites and applications. There are several third-party screen capture APIs and Plugins available in the market but here I'm going to show you a very simple solution. Yep that is to use Google PageSpeed Insights API to capture screen shot. And the fact that it doesn't requires registration or apikey is really good.

In general, Google PageSpeed Insights API is used to measure site performance. But you can also use it to capture screenshot of the website / webpage from a url. Let's see how to get the website screen shot from url using PageSpeed Insights API in PHP.

take screenshot of webpage in php

Using Google's PageSpeed Insights API:

Using Google PageSpeed Insights API to grab the webpage screen shot is very easy. All you have to do is call the api with params like this,

https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=$webpageURL&screenshot=true

where $webpageURL = url of the web page you need to take screenshot.

This api call will return the website screenshot for desktop view.

To take screenshot of mobile version use,

https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=$webpageURL&screenshot=true&strategy=mobile

Take Website Screenshot from URL with PHP:

Following is a small php example to capture the screenshot of a webpage using PageSpeed Insights API. Here we have a simple form where the user has to enter the url for which they need image preview. Once they submit the form, the url is passed to the api, which returns the response containing screenshot data.

index.php

<?php
if (!empty($_POST['url'])) {
    // get webpage url
    $url = $_POST['url'];
    // check if it is a valid url
    if (filter_var($url, FILTER_VALIDATE_URL)) {
        // send request to api
        $data = file_get_contents("https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=$url&screenshot=true");
        $data = json_decode($data, true);
        // get screenshot image
        $screenshot = $data['screenshot']['data'];
        $screenshot = str_replace(array('_','-'),array('/','+'),$screenshot);
    } else {
        $err = "Please enter a valid URL!";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Capture Website Screenshot in PHP - Demo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" >
    <link href="css/bootstrap.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div class="container">
    <div class="col-xs-8 col-xs-offset-2 well" style="background: none;">
        <form action="index.php" method="post">
            <div class="form-group">
                <input type="text" name="url" placeholder="Enter Webpage URL" class="form-control" />
            </div>
            <div class="form-group">
                <input type="submit" name="submit" value="Take Screenshot" class="btn btn-danger"/>
            </div>
        </form>
    </div>
    <?php if(isset($screenshot)) { ?>
    <div class="col-xs-8 col-xs-offset-2 text-center well" style="background: none;">
        <h2>Website Screenshot</h2><br/>
        <img src="<?php echo 'data:image/jpeg;base64,' . $screenshot; ?>" />
    </div>
    <?php } else if(isset($err)) { ?>
    <div class="col-xs-8 col-xs-offset-2 text-center well" style="background: none;">
        <?php echo $err; ?>
    </div>
    <?php } ?>
</div>
</body>
</html>

The above markup produce a php form with a text box and a submit button. Enter the url on the provided box and hit 'Take Screenshot' button.

take website screenshot php google api

If the provided url is a valid one, upon api request the website screenshot image will be displayed just below the form like this,

capture webpage screenshot php

That's it! Likewise, you can easily capture the webpage screenshot with PHP and Google API. I hope you like this tutorial. If you find it useful, please do share it on social media.

Also Read:

URL Shortener Service using PHP and Google API

On 9/26/2017 1 Comment so far

Hi! In today's post we will see about creating URL Shortener service using PHP and Google API. Google provides tons of APIs for users to easily complete several complicated tasks. And Google url shortener service (goo.gl) is one among them. In the past I have discussed about some other APIs like youtube api and google finance api. Now I'm going to show you about using google url shortener api service and generate shorten url using php.

php url shortener using google api

Google URL Shortener API:

The Google URL Shortener is a service that takes long URLs and makes them short with fewer characters to make the link easier to share on social networks or by email. With Google's URL Shortening API, you can create these short urls programmatically by sending the long url through the http request. Please note that the API has a daily limit of 1,000,000 requests for free - more than that goes to your billing.

In order to use google url shortener api, you must first get the api key and have to tag it with each of your REST calls.

  • To obtain the key, login to Google developer console
  • Create new or select an existing project
  • Click 'ENABLE API' and select APIs in the APIS & auth section
  • Choose 'URL Shortener API' and click 'ENABLE'
  • Under Credentials, generate a new key by selecting 'API key' option.

Creating URL Shortener Service with PHP and Google API:

The following PHP script quickly generates a short URL from a long URL by using the Google's URL Shortener API. So many examples around the Net uses only cURL method. So I have tried a different way in my tutorial. Here I use the file_get_contents() function to send the HTTP POST request to the api and retrieve the json response containing the short url.

<?php
$apikey = 'YOUR_API_KEY'; // change this to yours
$longurl = 'https://www.google.com/';
$data = array('longUrl' => $longurl);
$context = array(
    'http' => array(
        'method' => 'post',
        'header'=>'Content-Type:application/json',
        'content' => json_encode($data)
        )
    );
$context = stream_context_create($context);
$response = file_get_contents('https://www.googleapis.com/urlshortener/v1/url?key=' . $apikey, false, $context);
$json = json_decode($response, true);

echo 'The Long URL: ' . $json['longUrl'] . '<br/>';
echo 'The Shortened URL: ' . $json['id'];

// Output

// The Long URL: https://www.google.com/
// The Shortened URL: https://goo.gl/Njku
?>

In order to make http request via file_get_contents() function, we have to pass the headers and other options through a context. For that we have used the function stream_context_create() in the above code. It creates and returns a stream context that we need to make the http request to the web service. It takes up options as an associative array of associative arrays.

The API responds in json format containing shortened url stored in 'id'.

You can display the whole json response from the api in this way,

<?php
echo "<pre>";
print_r($response);

// Output

// {
//  "kind": "urlshortener#url",
//  "id": "https://goo.gl/Njku",
//  "longUrl": "https://www.google.com/"
// }
?>
Read:

This is how you can generate short urls with php and google api. Feel free to modify the code and add more features to the url service. Google really simplifies the task of shortening url and the good thing is that you don't have to maintain database on your own. I hope you like this tutorial. Please do not forget to share it in social networks.

SMS Gateway API Integration in PHP - Sending Text Messages

On 9/11/2017 Be the first to comment!

Hi! In this tutorial, we'll look at how to integrate sms api in php and send bulk text messages using simple php script. These days, increasing number of web applications uses SMS feature for product promotions, user authentication or sales and event notifications directly through their mobile phones. To send sms via php, you need to integrate an appropriate SMS gateway provider in your application. There are a number of SMS Service providers in the market and they offer APIs in various programming languages.

Here I'm going to show you how to integrate Textlocal SMS gateway in PHP.

sms gateway integration in php

Read: How to Create AJAX Search Engine using PHP and MySQL

Textlocal SMS API:

Textlocal is a bulk sms gateway that offers an easy and powerful messaging platform. It helps you maintain massive contact lists, compose rich multi-media messages and send sms in bulk. It has flexible APIs supporting different programming platforms.

Register with SMS Gateway:

In order to use Textlocal sms gateway in your web app, you must first register with their service and get your hash code.

Visit this link and signup for the sms service. It is necessary to provide details such as email address, mobile number and password for registration. At the beginning you will get 10 free sms credits which you can use for testing.

Read: User Login and Registration System using PHP and MySQL

Once you finish signing up, login and go to the Dashboard.

From there, navigate to 'Help' > 'All Documentation' page and get your API hash code.

You also need to download the API library textlocal.class.php. For that go to http://api.textlocal.in/docs/phpclass and click on 'Download' link on the righ side of the page.

SMS API Integration in PHP:

Extract and move 'textlocal.class.php' to your root folder. You have to include this class in your php code and use the sendSms() function to send text messages. To test the service, you can send sms from localhost. Here's the php code to do it.

<?php
require('textlocal.class.php');

$username = 'myemail@example.com'; // change this to your email address
$hashcode = 'xxxxxxx'; // change this to yours

$textlocal = new Textlocal($username, $hashcode);
$numbers = array(919999999999); // separate multiple numbers by comma
$sender = 'TXTLCL';
$message = 'Hi! This is a test message!!!';

try {
    $result = $textlocal->sendSms($numbers, $message, $sender);
    $data = json_decode($result, true);
    if($data['status'] == 'success'){
        echo 'SMS sent successfully!';
    }
} catch(Exception $e) {
    die('Error: ' . $e->getMessage());
}
?>

To send sms in bulk, use comma-delimited array list of mobile numbers. Also make sure the numbers are in international format i.e. country code followed by 10-digit mobile no. A maximum of 10,000 numbers are allowed at a time.

Run the above code and if all goes well, you will see success message. I received the sms within couple of seconds. Remember that you will only get ten sms credits under free account. So use it wisely to test the code and not run it in a loop.

Read: How to Import JSON into MySQL using PHP

By default, the Textlocal API will send the response as JSON. This is the response I received from the API.

{
    "balance": 8,
    "batch_id": 302329336,
    "cost": 1,
    "num_messages": 1,
    "message": {
        "num_parts": 1,
        "sender": "TXTLCL",
        "content": "Hi! This is a test message!!!"
    },
    "receipt_url": "",
    "custom": "",
    "messages": [
        {
            "id": "1200053892",
            "recipient": 919999999999
        }
    ],
    "status": "success"
}

The API returns a status field containing the message 'Success' or 'Failure'. You can use it to check if sms is sent or not.

You can also display the entire api response this way,

<?php
$result = $textlocal->sendSms($numbers, $message, $sender);
print_r($result);
?>

Read: Store and Retrieve Image from MySQL Database using PHP

Likewise you can send bulk sms in php via the Textlocal sms gateway. The entire process is simple and with few lines of code you can send bulk messages from your website. You can also use the cURL method and send an HTTP request to the sms server. I hope you like this tutorial. Please don't forget to share it in social media.

Currency Conversion in PHP using Google Finance API

On 7/18/2017 1 Comment so far

Hi! In this tutorial, let us see how to convert currency in PHP using Google Finance API. There are lots of currency conversion api's available but I'm going to use Google Finance here. Using the api you can easily convert money to your desired country currency. You have to send out http request to Google finance tagging with three values - amount, from currency and to currency code. And it sends back the response as HTML which you have to parse and extract the converted amount.

google api currency conversion php

Read: Store and Retrieve Image from Database in PHP & MySQL

PHP Function to Convert Currency:

Following is the currency convertor function I have created. The function takes up 3 params namely 'from_currency', 'to_currency' and 'amt' and makes call to google finance api. It uses file_get_contents() function to send http request and receives raw html response. Then it parses the html and returns the converted currency value.

<?php
function convert_currency($from_currency, $to_currency, $amt) {
    $from_currency = urlencode($from_currency);
    $to_currency = urlencode($to_currency);
    $amt = urlencode($amt);
    $data = file_get_contents("http://www.google.com/finance/converter?a=$amt&from=$from_currency&to=$to_currency");
    $data = explode('bld>', $data);
    $data = explode($to_currency, $data[1]);
    return round($data[0], 2);
}
?>

Function Usage:

echo convert_currency(USD, EUR, 100);

How to Convert Currency in PHP?

Now let me show you how to use the above function and implement currency convertor functionality in your application with a demo.

For that we'll need to create two php files, index.php and function.php.

In function.php, we keep the convert_currency() function we have created earlier. And in the index file, add a html form and input fields for amount and two dropdowns to choose from and to currency.

Read: Easy PHP Form Validation with Parsley.js Library

index.php

<?php
include_once "function.php";

//check if form is submitted
if (isset($_POST["submit"])) {
    $from_curr = $_POST["from_currency"];
    $to_curr = $_POST["to_currency"];
    $amount = $_POST["amount"];
    $result = convert_currency($from_curr, $to_curr, $amount);
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Currency Conversion in PHP</title>
</head>
<body>
    <h1>Currency Convertor</h1>
    <form action="index.php" method="post">
        <label for="amount">Amount</label> 
        <input type="text" name="amount" placeholder="Enter amount" value="<?php if(isset($_POST["amount"])){echo $_POST["amount"];} ?>" required />

        <?php
        $options = array(
            'GBP' => 'British Pound £',
            'EUR' => 'Euro €',
            'FRF' => 'French Franc (FRF)',
            'DEM' => 'German Mark (DEM)',
            'INR' => 'Indian Rupee (INR)',
            'USD' => 'US Dollar (USD)'
        );
        ?>
        <select name="from_currency">
        <?php foreach($options as $key => $value){ ?>
            <option value="<?php echo $key; ?>" <?php if(isset($_POST["from_currency"]) && ($_POST["from_currency"]==$key)){echo "selected";} ?>><?php echo $value; ?></option>
        <? } ?>
        </select>
        <br/><br/>
        <label>To</label> 
        <select name="to_currency">
        <?php foreach($options as $key => $value){ ?>
            <option value="<?php echo $key; ?>" <?php if(isset($_POST["to_currency"]) && ($_POST["to_currency"]==$key)){echo "selected";} ?>><?php echo $value; ?></option>
        <? } ?>
        </select>
        <input type="submit" name="submit" value="Convert" />
    </form>

    <span><h2><?php if (isset($result)) { echo $amount . " " . $from_curr . " = " . $result . " " . $to_curr; } ?></h2></span>
</body>
</html>

function.php

<?php
function convert_currency($from_currency, $to_currency, $amt) {
    $from_currency = urlencode($from_currency);
    $to_currency = urlencode($to_currency);
    $amt = urlencode($amt);
    $data = file_get_contents("http://www.google.com/finance/converter?a=$amt&from=$from_currency&to=$to_currency");
    $data = explode('bld>', $data);
    $data = explode($to_currency, $data[1]);
    return round($data[0], 2);
}
?>

So user must enter the amount value, from and to currency code and submit the form. And the script sends http request to Google finance, get response, extract and display the converted amount on the page.

Read: How to Get YouTube Video Details from URL in PHP

Likewise you can implement currency convertor in php application. I hope you find this useful. If you like this tutorial, please don't forget to share it in social media. Meet you in another interesting post.

Get YouTube Video Title, Description & Thumbnail from URL in PHP

On 7/04/2017 Be the first to comment!

Hi! In this tutorial I'm going to show you how to get youtube video details like title, description, thumbnail image etc from a video url using php script. With the help of Google's YouTube Data API you can fetch information about youtube videos. In general each youtube video will have a specific 'ID' associated to it. To retrieve data about a video you have to pass this video id while making the api call. And the api in turn returns back the video data as json response.

YouTube API is not only helpful to fetch basic video info but also let you create playlists, channels, implement youtube search and much more.

Get YouTube Data API Key

YouTube Data API is free to use but first you must get access to it. You need a Google account to get api access and is provided in the form of an api key.

1. To get api-key, go to https://console.developers.google.com and login with your Google account.

2. Once you are in, create a new project and click on 'ENABLE API' link at the top.

3. Now scroll down to 'Youtube APIs' section and select 'Youtube Data API'.

get youtube data api key 1

4. Then click on the 'ENABLE' link at the top-right side of the page to enable youtube data api for your account.

get youtube data api key 2

5. Once enabled, select 'Credentials' on the left-pane. Under credentials click on 'Create credentials' button and choose 'API key' in the dropdown.

get youtube data api key 3

7. Your api key will be generated and shown in a popup. Save the key to a text file for later use.

get youtube data api key 4

Done! Now we have the key to access youtube api. Let's move on to the coding part.

Fetching YouTube Video Information

In general YouTube videos share a common url structure and they look like this.

https://www.youtube.com/watch?v=VIDEO_ID

Where 'VIDEO_ID' represents the individual video id.

You have to take this video id from the youtube video url and use it to fetch details.

Like I already said, to fetch video information you have to call the youtube api. And you must also send the corresponding 'VIDEO_ID' and 'parts' of the information you need to retrieve. Following is the php script to do it.

PHP Script to Get YouTube Video Details

<?php
$videoid = 'H4Jx4oefSjw'; // change this
$apikey = 'API_KEY'; // change this

$json = file_get_contents('https://www.googleapis.com/youtube/v3/videos?id=' . $videoid . '&key=' . $apikey . '&part=snippet');

$data = json_decode($json, true);

echo "<pre>";
print_r($data);
?>

The above snippet will produce an output like this.

Array
(
    [kind] => youtube#videoListResponse
    [etag] => "m2yskBQFythfE4irbTIeOgYYfBU/YJEU8MCit4Jt-7o2NPm81zgElAQ"
    [pageInfo] => Array
        (
            [totalResults] => 1
            [resultsPerPage] => 1
        )

    [items] => Array
        (
            [0] => Array
                (
                    [kind] => youtube#video
                    [etag] => "m2yskBQFythfE4irbTIeOgYYfBU/Sx66nqOT7ouBnClI9ImzyEA1n90"
                    [id] => H4Jx4oefSjw
                    [snippet] => Array
                        (
                            [publishedAt] => 2013-08-01T04:12:47.000Z
                            [channelId] => UCj4LfrxdH7TnUZlyHOKgL5A
                            [title] => 01. Programming in Objective-C - Introduction
                            [description] => Ever wondered what Objective-C actually is? Historically, it was the first attempt to make C objectified. C++ came later. NextStep, and now OSX, popularized this very powerful language. So sit back, as Yari D`Areglia takes you through the first steps in getting started with this language.
                            [thumbnails] => Array
                                (
                                    [default] => Array
                                        (
                                            [url] => https://i.ytimg.com/vi/H4Jx4oefSjw/default.jpg
                                            [width] => 120
                                            [height] => 90
                                        )

                                    [medium] => Array
                                        (
                                            [url] => https://i.ytimg.com/vi/H4Jx4oefSjw/mqdefault.jpg
                                            [width] => 320
                                            [height] => 180
                                        )

                                    [high] => Array
                                        (
                                            [url] => https://i.ytimg.com/vi/H4Jx4oefSjw/hqdefault.jpg
                                            [width] => 480
                                            [height] => 360
                                        )

                                    [standard] => Array
                                        (
                                            [url] => https://i.ytimg.com/vi/H4Jx4oefSjw/sddefault.jpg
                                            [width] => 640
                                            [height] => 480
                                        )

                                    [maxres] => Array
                                        (
                                            [url] => https://i.ytimg.com/vi/H4Jx4oefSjw/maxresdefault.jpg
                                            [width] => 1280
                                            [height] => 720
                                        )

                                )

                            [channelTitle] => Dilan Damith Prasanga I.G.
                            [tags] => Array
                                (
                                    [0] => Objective-C (Programming Language)
                                    [1] => Programming In Objective-C
                                    [2] => Programming Language (Literary Genre)
                                )

                            [categoryId] => 27
                            [liveBroadcastContent] => none
                            [localized] => Array
                                (
                                    [title] => 01. Programming in Objective-C - Introduction
                                    [description] => Ever wondered what Objective-C actually is? Historically, it was the first attempt to make C objectified. C++ came later. NextStep, and now OSX, popularized this very powerful language. So sit back, as Yari D`Areglia takes you through the first steps in getting started with this language.
                                )

                        )

                )

        )

)

As you can see, we have decoded the json response to php array and it contains details like video title, description, thumbnail urls, view count, channel id and much more. Now you must parse this array to extract individual data like title, description etc.

To Get YouTube Video Title,

<?php echo $data['items'][0]['snippet']['title']; ?>

To Get YouTube Video Description,

<?php echo $data['items'][0]['snippet']['description']; ?>

To Get YouTube Video Thumbnail URL,

<?php $data['items'][0]['snippet']['thumbnails']['default']['url']; ?>

YouTube stores four different types of thumbnails at various resolutions for a single video. Above, I have taken the default thumbnail image url.

Once you've got the video info, use it as per your liking. Here is a simple example in which I have displayed video details in a web page.

Example

<?php
echo '<h1>Title: ' . $data['items'][0]['snippet']['title'] . '</h1>';
echo '<img src="' . $data['items'][0]['snippet']['thumbnails']['default']['url'] . '" style="float:right;"/>';
echo '<p>' . $data['items'][0]['snippet']['description'] . '</p>';
?>
fetch youtube video title description and thumbnail in php

I hope now you have clear understanding of using youtube data api to fetch youtube video details using php. This is just a taste of what youtube api can do. Obviously there's more to it. I'll cover the api more in detail in future posts. If you like this tutorial, don't forget to share it in social media.

Integrate reCAPTCHA in Codeigniter Tutorial

On 3/27/2017 Be the first to comment!

Hi! Let's see How to integrate reCAPTCHA in Codeigniter Application. This will help protect your codeigniter websites from spam and bots. Google reCAPTCHA effectively blocks out bot access but the old recaptcha is not very user-friendly. It requires you to fill out a textbox with the characters you see on an image. Not to mention the captcha text is difficult to read even for humans. Later a new version of reCAPTCHA named 'I'm not a robot' has been released by Google. It is meant to be gentle on humans and hard on bots.

In this new recaptcha all you have to do is to tick a checkbox and be done. In fact it's much more effective in controlling spam and improves user-experience without compromise.

Also Read:

How to Integrate reCAPTCHA in CodeIgniter?

In order to integrate Google reCAPTCHA in your Codeigniter application, you have to first register the specific site with Google. After registration you will be provided with two keys namely Site & Secret key.

The 'Site Key' should be used for displaying recaptcha widget on your site and 'Secret Key' for captcha verification.

register website with recaptcha

For testing purpose Google let you to run recaptcha from localhost. I'll show you how to do this.

  1. Visit here and register the codeigniter site you wish to integrate recaptcha.
  2. You have to enter 'Label' and 'Domains' details in the registration form.
  3. Label is just for your understanding so you can simply provide site name here.
  4. In 'Domains' box enter the domain name. To test recaptcha from local machine enter 'localhost'.

Click on 'Register' and you will be provided with a set of keys. Save the keys in a text file. You will need them for implementing captcha code.

Adding reCAPTCHA to Form:

For using recaptcha in a form load the api library first.

<script src='https://www.google.com/recaptcha/api.js'></script>

Then add this snippet to display recaptcha widget wherever you want.

<div class="g-recaptcha" data-sitekey="your-site-key"></div>

For better understanding let us create user feedback form in codeigniter and add recaptcha to it. You need a controller and view file for this.

The View ('recaptcha_demo_view.php'):

The view file contains a feedback form with recaptcha verification. The form will be processed only when user verifies captcha.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeIgniter Recaptcha Demo</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
    <script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
    <div class="container" style="margin-top: 20px;">
        <div class="col-xs-6 col-xs-offset-3 well" style="background:none;">
        <?php echo form_open("recaptcha_demo/index"); ?>
            <div class="form-group">
                <textarea name="feedback" placeholder="Your feedback..." class="form-control" rows="4"><?php echo set_value('feedback'); ?></textarea>
                <span class="text-danger"><?php echo form_error('feedback'); ?></span>
            </div>
            <div class="form-group">
                <div class="g-recaptcha" data-sitekey="your-site-key"></div>
                <span class="text-danger"><?php echo form_error('g-recaptcha-response'); ?></span>
            </div>
            <div class="form-group">
                <button type="submit" name="submit" class="btn btn-lg btn-danger">Send Feedback</button>
            </div>
        <?php echo form_close(); ?>
        <?php echo $this->session->flashdata('msg'); ?>
        </div>
    </div>
</body>
</html>

The Controller ('recaptcha_demo.php')

In controller we have an index() function to which the form is submitted and a custom callback to verify captcha input.

<?php
class recaptcha_demo extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form','url'));
        $this->load->library(array('session', 'form_validation'));
    }
    
    function index()
    {
        $this->form_validation->set_rules('feedback', 'Feedback', 'required');
        $this->form_validation->set_rules('g-recaptcha-response', 'g-recaptcha-response', 'callback_captcha_validation');

        if ($this->form_validation->run() == FALSE)
        {
        
            $this->load->view('recaptcha_demo_view');
        }
        else
        {
            $this->session->set_flashdata('msg','<div class="alert alert-success text-center">Thanks for your Feedback! We got it!!!</div>');
            redirect('recaptcha_demo/index');
        }
    }
    
    function captcha_validation()
    {
        $secret_key = 'your-secret-key'; // change this to yours
        $url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . $secret_key . '&response='.$_POST['g-recaptcha-response'];
        $response = @file_get_contents($url);
        $data = json_decode($response, true);
        if($data['success'])
        {
            return true;
        }
        else
        {
            $this->form_validation->set_message('captcha_validation', 'Please confirm you are human');
            return false;
        }
    }
}

Done! Now run the file and you will see a nice user feedback form with recaptcha at the bottom.

integrate recaptcha in codeigniter

Fill-in your feedback, tick the recaptcha checkbox and click Send Feedback.

codeigniter recaptcha tutorial

If form validation goes right you will be shown with a success message like this.

how to use recaptcha in codeigniter

On the other hand if you don't confirm captcha and submit the form, you will be asked to confirm captcha like this.

codeigniter recaptcha form validation

You can also implement recaptcha in php form, just check the tutorial.

Also Read:

That's it! You have successfully integrated Google reCAPTCHA in CodeIgniter. Implement recaptcha in codeigniter applications you build and stop spammers bombarding your site. Please make sure to use site & secret key with yours for this to work. If you have any trouble using this code please let me know in comments section.

Contact Form

Name

Email *

Message *