JavaScript and jQuery script to get current URL

In this article, I am going to explain two ways to get current URL using JavaScript and jQuery code snippet.

1) Get current URL using JavaScript: In below script, I have created a function alertURL() that will fetch the current URL using window.location.href method of the JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Get Current Page URL</title>
</head>
<body>
<input type="button" id="alerturl" value="Print Current URL" onclick="alertURL();">

<script type="text/javascript">
function alertURL(){
 var cur_loc = window.location.href;
 alert(cur_loc);
}
</script>
</body>
</html>

Output:


2) Get Current URL using jQuery: 
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Get Current Page URL</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body>
<input type="button" id="alerturl" value="Print Current URL">
<span id="print_msg"></span>
<script type="text/javascript">
$(document).ready(function(){
 $('#alerturl').click(function(){
  var current_page = $(location).attr('href');
  $('#print_msg').html('Your current URL is: '+current_page);
 });
});
</script>
</body>
</html>

Output:

What is the use of the @ symbol in PHP?

The @(the at symbol) symbol in PHP is used to suppress the error reporting for the expression prepended with the @ symbol. However; if track_errors feature is enabled on your server then, any error message generated by the expression will be saved in $php_errormsg variable and this variable gets overwritten on each error. I would suggest, do not use @ symbol, this is not a good practice. Because this symbol does not disappear the error permanently, it just hide the error from the visitors and also is difficult for developer to identify the error.

Let have look at an example below:

<?php 
echo $_GET['user_id'];
echo @$_GET['user_id'];
?>

The first statement in above code will throw Notice: Undefined index error, however, the second statement will not throw any error at all.
Notice: Undefined index: user_id in F:\localhost\htdocs\test\test.php on line 2

I hope, this tutorial will help you. Please feel free to add your views in the comment box below.


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.


<?php
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 = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" . $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');
 print_r($result);
?>

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);
$con->close();


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 = 
       "http://example.com/index.php?url=" + 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 106.223.197.90
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 106.223.197.90
deny from 106.223.197.91
deny from 106.223.197.92
allow from all

Ban a range of IPs

If you want to ban a full range of  IPs for example 106.223.197.1 to 106.223.197.225, 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 airtel.com
allow from all