Friday 30 October 2015

How to calculate latitude and longitude for a given address and vise-versa in php

Hi Everybody,

In this blog we will discuss about how to calculate latitude and longitude for a given address and vise-versa in php.

Get latitude and longitude from a  given address(Geocode):-


        $address = "790 Castro St, Mountain View, CA";

        $formAddr = str_replace(' ','+',$address);

        $geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$formAddr.'&sensor=false');

        $output= json_decode($geocode);

        if(is_array($output )&& $output ['Status']['code']==200) {

                    $latitude = $output->results[0]->geometry->location->lat;

                    $longitude = $output->results[0]->geometry->location->lng;

       }

Get address from latitude and longitude(Reverse Geocode):-


       $lat = 37.3874353;
        $lng = -122.0835459;
        $revGeocode = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lng&sensor=false");
        $output = json_decode($revGeocode);
        if(is_array($output )&& $output ['Status']['code']==200) {
                    $address = $output->results[0]->formatted_address;
        }

Let me know if you face any problem in this.
Thanks.

Friday 23 October 2015

How to change format of mobile number in US format (XXX) XXX-XXXX using Jquery

Hi Everybody,

In this blog we will discuss about how to change format of mobile number in US format (XXX) XXX-XXXX using Jquery.

For this we have to code our Html and Jquery, given below

Html Code


<form id="example-form" name="my-form">
    <label>Phone number:</label><br />
    <!-- I used an input type of text here so browsers like Chrome do not display the spin box -->
    <input id="phone-number" name="phone-number" type="text" maxlength="14" placeholder="(XXX) XXX-XXXX" /><br /><br />
    <input type="button" value="Submit" />
</form>

Jquery Code

$('#phone-number', '#example-form')

.keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);

// Auto-format- do not expose the mask as the user begins to type
if (key !== 8 && key !== 9) {
if ($phone.val().length === 4) {
$phone.val($phone.val() + ')');
}
if ($phone.val().length === 5) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 9) {
$phone.val($phone.val() + '-');
}
}

// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 || 
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.bind('focus click', function () {
$phone = $(this);
if ($phone.val().length === 0) {
$phone.val('(');
}
else {
var val = $phone.val();
$phone.val('').val(val); // Ensure cursor remains at the end
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});

Note:-After change mobile number in this format, best practice is this you have to save only 10 digit mobile number in your database(without (, ), and space).

For this if your server side script written in php then use below code to convert this US format mobile number to simple 10 digit number(for save in database) .

PHP Code

preg_replace("/[^0-9]/","",$mobile)

here $mobile is mobile input field you receive by Get or Post method after submit this form.

Thanks for read this blog, if you any question or suggestion please type in comment box.

Friday 16 October 2015

Auto populate city and state using zip code(USA) in Laravel 5.1

Hi Everybody,

In this blog we will discuss how to auto populate USA city and state using zip code in Laravel 5.1.
For this we have to use google api for find city and state using zip code.

1. Routes


routes.php
Route::post('get/citystate', 'CityStateController@getCityState');

2. Controller

CityStateController.php

<?php

namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;

class AccountController extends Controller
{
 public function getCityState($blnUSA = true) {
        $data = Input::all();
        $zip = $data['zip'];
        $url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $zip . "&sensor=true";
        $address_info = file_get_contents($url);
        $json = json_decode($address_info);
        $city = "";
        $state = "";
        $country = "";
        $arrReturn = array();
        if (count($json->results) > 0) {
            //break up the components
            $arrComponents = $json->results[0]->address_components;

            foreach($arrComponents as $index=>$component) {
                $type = $component->types[0];

                if ($city == "" && ($type == "sublocality_level_1" || $type == "locality") ) {
                    $city = trim($component->long_name);
                }
                if ($state == "" && $type=="administrative_area_level_1") {
                    $state = trim($component->short_name);
                }
                if ($country == "" && $type=="country") {
                    $country = trim($component->short_name);

                    if ($blnUSA && $country!="US") {
                        $city = "";
                        $state = "";
                        break;
                    }
                }
                if ($city != "" && $state != "" && $country != "") {
                    //we're done
                    break;
                }
            }
        }
        return $arrReturn = array("city"=>$city, "state"=>$state, "country"=>$country);
    }

}

3. View

citystate.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery.js"></script>
<script>

function is_int(value){
    if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) {
        return true;
    } else {
        $("#city").val(''); /* Fill the data */
        $("#state").val('');
        return false;
    }
}

$("#zip").keyup(function() {
    $(".zip-error").hide(); /* In case they failed once before */
    var el = $(this);
    if ((el.val().length == 5) && (is_int(el.val()))) {
        $.ajax({
            url: '/get/citystate',
            type: "POST",
            data: "zip=" + el.val(),
            success: function(result, success) {
                $("#city").val(result['city']); /* Fill the data */
                $("#state").val(result['state']);
                if($("#city").val()=="" || $("#state").val()==""){
                    $(".zip-error").show(); /* Ruh row */
                }else{
                    $(".zip-error").hide(); /* In case they failed once before */
                }
            },
            error: function(result, success) {
                $(".zip-error").show(); /* Ruh row */
            }
        });
    }else{
        $(".zip-error").show(); /* Ruh row */
    }
});
</script>
</head>
<body>
<div class="container">
<div class="form-group">
<div class="row">
    <div class="col-md-4 mrgn_t_10">
        <input type="text" pattern="[0-9]*"  maxlength="5" class="form-control indent_zero" id="zip" placeholder="ZIP" name="zip" value=""><p class="zip-error" style="display: none">Not a real zip code.</p></div>

  <div class="col-md-4 mrgn_t_10">
  <input type="text" class="form-control indent_zero" id="city" placeholder="CITY" name="city" value=""></div>
  
  <div class="col-md-4 mrgn_t_10">
      <input type="text" class="form-control indent_zero" id="state" placeholder="STATE" name="state" value=""></div>
</div>
</div>
</div>
</body>
</html>

If you have any query you can post it in comment.
Thanks.

Friday 9 October 2015

How does Upgrading PHP Solve Security Issues?

Hi Everybody,

In this blog we will discuss about security in PHP.

PHP is a popular language and has been more accepted than any other as the platform of choice for the web. PHP has evolved that it is now the run time environment backing many of the world’s highest traffic web sites and largest open source projects such as Drupal, Magento and Wordpress.

But as dependent these businesses are on PHP,  they constantly resist adoption of newer versions. They see adoption and change as a risk to losing their market share and end-user trust. It is a struggle leading to a history making security threat to today's web.

It Starts with Awareness

Many talk about writing secure PHP code. But not much information is written about why upgrading PHP versions makes web applications more secure. The first step is to be aware of the security vulnerabilities.

Threat Types

DoS  -  In a denial-of-service DoS attack, an attacker attempts to prevent legitimate users from accessing information or services. By targeting a computer and its network connection or other services that rely on the affected computer. Sometimes the attacker can inject and execute arbitrary code while performing a DoS attack in order to access critical information or execute commands on the server.

Code Execution  - an attacker's ability to execute any commands of the attacker's choice on a target machine or in a target process. It is the most powerful effect a bug can have because it allows an attacker to completely take over the vulnerable process. From there the attacker can potentially take complete control over the machine the process is running on.

Overflow  - more commonly known as stack overflows occur when variable size data is copied into fixed length buffers located on the program stack without any bounds checking. Vulnerabilities of this class are generally considered to be of high severity since their exploitation would mostly permit arbitrary code execution or Denial of Service. Rarely found in interpreted platforms, code written in C and similar languages is often ridden with instances of this vulnerability.

Memory Corruption  -  Using memory beyond the memory that was allocated buffer overflow. If an array is used in a loop, with incorrect terminating condition, memory beyond the array bounds may be accidentally manipulated. Buffer overflow is one of the most common programming flaws exploited by computer viruses.

Sql Injection - SQL Injection is one of the many web attack mechanisms used by hackers to steal data from organizations. It is perhaps one of the most common application layer attack techniques used today. It is the type of attack that takes advantage of improper coding of your web applications that allows hacker to inject SQL commands into say a login form to allow them to gain access to the data held within your database.  

XSS  -   Cross-site Scripting (XSS) refers to client-side code injection attack wherein an attacker can execute malicious scripts (also commonly referred to as a malicious payload) into a legitimate website or web application. XSS is among est the most rampant of web application vulnerabilities and occurs when a web application makes use of invalidated or decoded user input within the output it generates.

Directory Traversal  -  Properly controlling access to web content is crucial for running a secure web server. Directory traversal is an HTTP exploit which allows attackers to access restricted directories and execute commands outside of the web server’s root directory.

HTTP Response Splitting  -   HTTP response splitting occurs when data enters a web application through an untrusted source, most frequently an HTTP request. The data is included in an HTTP response header sent to a web user without being validated for malicious characters.

Bypass something  -  bypass vulnerabilities of authentication, web server limitations or operating system limits are generally caused by programmers assuming that users will behave in a certain way and failing to foresee the consequences of users doing the unexpected.

Gain Information - Intruders may be able to gain access to specific information stored on the host, including security settings. This could result in potential misuse of the host by intruders.  

Gain Privileges  - Privilege escalation is the act of exploiting a bug, design flaw or configuration oversight in an operating system or software application to gain elevated access to resources that are normally protected from an application or user. The result is that an application with more privileges than intended by the application developer or system administrator can perform unauthorized actions.
CSRF - Cross-site request forgery, also known as a one-click attack or session riding and abbreviated as CSRF (sometimes pronounced sea-surf) or XSRF, is a type of malicious exploit of a website whereby unauthorized commands are transmitted from a user that the website trusts.

File Inclusion - File inclusion vulnerability is a type of vulnerability most often found on websites. It allows an attacker to include a file, usually through a script on the web server.

Multiple Exploitation Fronts

Being aware of the types of threat is not enough. What many don't  realize is a security threat can take on place on multiple fronts. They can be independent or interdependent.

This is one of the facts that many open source projects miss. They assume that once a piece of code is patched then the security problem has been removed forever. Not recognizing that it still remains but only has been obstructed by a re-factoring of a singularly obvious instance. A threat can re-occur over time through code base changes. In a project with  thousands of contributors both core and third-party. The chances of the same exploit being written into the code base several times over is extremely high.

Web Server - A web server is an information technology that processes requests via HTTP, the basic network protocol used to distribute information on the World Wide Web. The term can refer either to the entire computer system, an appliance, or specifically to the software that accepts and supervises the HTTP requests.

Server Operating System - The operating system is the most important program that runs on a computer. Every general-purpose computer must have an operating system to run other programs and applications. Operating systems perform basic tasks, such as recognizing input from the keyboard, sending output to the display screen, keeping track of files and directories on the disk, and controlling peripheral devices such as disk drives and printers.

Code run-time execution - A run time program is an application that is distributed for use. Code run time environments can be one of  several  interpreters, compilers and virtual machines being the most common.

PHP interpreter

Web Server Vulnerabilities

You can find hundreds of tutorials and best practices for securing PHP on the web server. You'll also find that the popular  web servers like Apache are in a constant state of flux and  newer versions being readily adopted.

There are five vulnerabilities fixed in the latest release of the Apache Web server, including a buffer overflow and several denial-of-service vulnerabilities. Fixes for these flaws have landed in the developer release of the server

This trust in new versions is something that the PHP interpreter does not enjoy.
There are five vulnerabilities fixed in the latest release of the Apache Web server, including a buffer overflow and several denial-of-service vulnerabilities. Fixes for these flaws have landed in the developer release of the server, 2.4.10-dev.

Code Vulnerabilities

The big three CMS are constantly pushing for users to upgrade to close security holes allowed in code. They create message applications designed for upgrading extensions. They have mailing lists with subscribers numbering in the thousands.  All dedicated to maintaining security within this area.


PHP Interpreter Vulnerabilities

This is the area where information is weak. Where upgrading PHP can increase security by removing an exploitation front. decreasing threat levels in others. Because in the first categories there are hundreds of developers and bloggers  pointing fingers at  the other items. Yet they never mention upgrading the PHP version that also might be responsible for making the exploit possible.  One might suppose they either assume version upgrades or don't care.

Honestly, I think that the largest failure in this area is hubris. Developers and DevOps can show-off their intelligence with knowledge of code and server security. But they are well aware of the fact that version upgrades can break many things and make them look bad.

Even in the face of a warning upgrading PHP will be delayed and hopefully the responsibility can be handed off to the web hosting company. The  hosting company on the other side is of course waiting for a catastrophe or land slide of complaints before acting.  The resulting  stalemate of inaction is what hackers count on for access.

A newly reported critical vulnerability in PHP enables would-be cyber criminals to steal source code or inject and run malware in PHP applications by adding command-line parameters to URLs. Fortunately, The PHP Group has announced updates to PHP that its says eliminates the vulnerability.

The hosting company might make a newer version of PHP available but they will not enforce it's use.  In the mean time script kiddie bots are searching for sites to exploit.



The state of PHP Security

Note  that the year of 2007 was very high in vulnerabilities and also was the slowest adoption rate of a new version of PHP. One only has to extrapolate to see that the increase in threats was due to less secure versions remaining available for an overly long period.

When you don't  take in account the upgrading of PHP into your security efforts then you are pouring them into a leaky bucket. It's is only a matter of time before a widespread threat event. Imagine if your code is a major player in supporting the 30% or so of websites that use a CMS.