Get City, State and Country name by latitude and longitude using Google Map API and PHP

In this blog, I'am going to write a function to get City, State and Country name by latitude and longitude using Google Map API and PHP. I have created a function called get_city_state_country(), that will help us getting city, state and country name.

Below function get_city_state_country() accept two parameters. First parameter is used for latitude of the location and second one is for longitude. When you call this function in your script by passing latitude and longitude, it will return an array with city name, state name and country name. If no result found by Google Map API then it will return blank array with city, state and country keys.

public function get_city_state_country($latitude, $longitude) {
        $output = array('city' => '', 'state' => '', 'country' => '');
        $agent = 'Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0';
        $ch = curl_init();
        $url1 = "" . $latitude . "," . $longitude . "&sensor=false&key=YOUR KEY HERE";
        curl_setopt($ch, CURLOPT_USERAGENT, $agent);
        curl_setopt($ch, CURLOPT_URL, $url1);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $val = curl_exec($ch);
        $locs = json_decode($val);
        if ($locs->status != 'ZERO_RESULTS' && isset($locs->results[0])) {
            foreach ($locs->results[0]->address_components as $l) {
                if ($l->types[0] == 'locality') {
                    $output['city'] = $l->long_name;
                if ($l->types[0] == 'administrative_area_level_1') {
                    $output['state'] = $l->long_name;
                if ($l->types[0] == 'country') {
                    $output['country'] = $l->long_name;
        return $output;
 $result = get_city_state_country('28.535517','77.391029');

Please note that, before using this function, make sure that curl() function is enabled on your server. Without CURL this function throw error and will not work. And you also have pass your Google Map account in 'key' parameter to make it work.

How to add days to date using PHP

Whether, you are printing a future date or you are creating a report in which, you need to create a weekly report or a monthly report and you want to add n number of days in current date to create your desired report then in such conditions this blog is useful for you.

So lets start with the ways, we can add days into date by using PHP language. There couple of ways, first one is, If you are using PHP 5.3 or greter version then you can add days to date with DateInterval() function. And if you are using lower version than PHP 5.3 then you should use PHP inbuilt function date() and date() function also works in latest PHP versions.

PHP 5.3
$Date1 = '2019-04-10';
$date = new DateTime($Date1);
$date->add(new DateInterval('P1D')); // Here P1D means a period of 1 day
$Date2 = $date->format('Y-m-d');

and the second method is:
$Date = date('Y-m-d', strtotime("2019-04-10" . " + 1 day")); // Here +1 is used for adding 1 day into date. If you add -1 instead of +1 it will print 09-04-2019

Hope you will like this blog. Please let me know, your comments below.

A small guide about UTF-8 Encoding in PHP and MySQL

As a PHP developer, we often use MySQL as a database for our projects to store data on the server and we always use English as a language while storing data into the table. In some cases like storing some special characters or symbols which are not into defined into the character set you have enabled for your table, then MySQL store that special characters into bad encoding and when you fetch the record and print that you will see some bad characters instead of special characters.

To resolve this problem, we use to set charecter set while storing special charecters and while fetching it.

There are two methods to set charecter set:
1) Via PHP function
2) Via MySQL Query

1) Via PHP function: PHP(MySQLi Driver) has two functions to set charecter set. First one is mysqli_set_charset(), which is procedural approach and second one is $conn->set_charset which is object oriented approach and $conn is connection object which is importent to use in object oriented approach.

mysqli_set_charset($conn, "utf8"); /* Procedural approach */
$conn->set_charset("utf8");        /* Object-oriented approach */

2) Via MySQL Query: In MySQL, you have run below query before inserting, updating or fetching records to take effect on current query.

SET NAMES 'utf8';

Full PHP script:
<?php $servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
mysqli_query("SET NAMES 'utf8'");
$sql = "SELECT name FROM users";
$result = $conn->query($sql);

How to use MySQL FIND_IN_SET() Function in Codeigniter

Hello Guys,

Today, I am going to share a very small but useful tutorial with you about how to use MySQL FIND_IN_SET() function in codeigniter. Let's say, you are creating a product listing page and the tag ids  associated with the product are stored in a comma separated column and you want to fetch all records of tag id 5, in this case we use MySQL FIND_IN_SET() function.

Now the question is how to use FIND_IN_SET() function in Codeigniter?

Without wasting your time lets quickly walk through the code:
$this>db->select('name')->from('product')->where("FIND_IN_SET('5',post_tags) > 0")->get()->result();

How to encode URL in JavaScript?

If you are looking to encode an URL that have an query string (like '?name=akhilesh shukla') on one of your page and you don't want your visitor's to see that or in some case like you want to redirect your visitor to a link where the link accept parameters in encoded format then you must have to encode the parameter before redirecting user to that particular link.

Encode URL using encodeURIComponent() Method:
var param = 'Akhilesh Shukla #fhfd 547';
var linkURL = 
       "" + encodeURIComponent(param);

In above example, I have encoded the param variable. Though, encoding URL can also be done using encodeURI() method. However, encodeURI() does not encode special characters like #,/,? etc.

Recommended article: How to remove query string parameter using jQuery

Block bad IP addresses from accessing your website with .htaccess

If you want to block a bad IP address from accessing your website, and you have the IP address, host name or you know ISP of the visitor then you can easily block the visitor accessing your website with .htaaccess file. You can even secure a part of the website from accessing by placing a .htaccess file in the folder and the code into it.

A small tips: If you have WordPress website in which you want placing your code to block users then i would recommend that always place code after or before # BEGIN WordPress  and # END WordPress lines.

htaccess code to ban an IP

To ban a single IP place the below code into your .htaccess file and upload it to the root folder on your server.
order allow,deny
deny from
allow from all

In above example, I have blocked this IP to accessing my website and now this IP cannot visit any part of my website. However, in future if I want to give this IP acccess again, then I can remove the line from my htaccess and the IP can access the website again. The syntax to block a visitor is deny from the IP/ISP.

How to ban multiple IP addresses?

If you want to ban multiple IPs from accessing your website then also the syntax is same and you will need to add them in new line as below:
order allow,deny
deny from
deny from
deny from
allow from all

Ban a range of IPs

If you want to ban a full range of  IPs for example to, you can easily ban as below:
order allow,deny
deny from 106.223.197.
allow from all

Ban an ISP in htaccess

Blocking an ISP is same as blocking an IP, you will need to replace the IP with the ISP. See example:

order allow,deny
deny from
allow from all

Add custom class to WordPress menu using wp_nav_menu function

WordPress has a very good functionality of creating menu by dragging and dropping to required places and creating child or sub child menu in same way, that helps a layman to create menu very easily within a minute or two. However; if you are a developer and you want to go deeper in the functionality such as if you want to add a class to the parent UL or you want to add an ID to the parent UL tag then you will need to edit the source code.

Generally, we call wp_nav_menu() as following:
<?php wp_nav_menu( array('theme_location' => 'primary','menu_id' => 'mainHdrMenuId','menu_class' => 'hdrnavLst pull-right', )); ?>

In Above example, I have used 'primary' navigation in theme_location parameter that i already have created a menu in WordPress admin and also assigned 'mainHdrMenuId' as menu id and added two class in the menu_class parameter However; the classes and ids will be applied to the parent div section and not in UL tag.

If you want to add the class in UL section then you must have to define ul as a container in wp_nav_menu() function and then the defined id and classes will applied only to ul tag not to the parent div that WordPress by default add. See the example below:
<?php wp_nav_menu( array('theme_location' => 'primary','container'=> 'ul', 'menu_id' => 'mainHdrMenuId','menu_class' => 'hdrnavLst pull-right', )); ?>

I Hope this trick will help you. Please share your feedback in the comment box below.

How to get last insert ID in Codeigniter

I assume, you must be creating a website where you are looking to get last insert id of executed INSERT query in parent table and then you want to store the last inserted ID in your child table as a foreign key.

In this post, i am going to share with you guys a small Codeigniter method that will help you to get last inserted id.

Here it is:

Run this peace of code after insert query and this method will return you last inserted id of the executed query.

I hope this post will help.