Monthly Archives: November 2014

Distance between two Latitudes and Longitudes – Part 2

This series is about code in various languages that will calculate the distance between two latitudes and longitudes. This article is for the Javascript code.

Code courtsey : GeoDataSource

/*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*::                                                             :*/
/*::  This routine calculates the distance between two           :*/
/*::  points (given the latitude/longitude of those points).     :*/
/*::  It is being used to calculate the distance between two     :*/
/*::  locations using GeoDataSource(TM) Products                 :*/
/*::                                                             :*/
/*::  Definitions:                                               :*/
/*::    South latitudes are negative,                            :*/
/*::    east longitudes are positive                             :*/
/*::                                                             :*/
/*::  Passed to function:                                        :*/
/*::    lat1, lon1 = Latitude and Longitude of point 1           :*/
/*::                 (in decimal degrees)                        :*/
/*::    lat2, lon2 = Latitude and Longitude of point 2           :*/
/*::                 (in decimal degrees)                        :*/
/*::    unit = the unit you desire for results                   :*/
/*::           where: 'M' is statute miles                       :*/
/*::                  'K' is kilometers (default)                :*/
/*::                  'N' is nautical miles                      :*/
/*::  Worldwide cities and other features databases with         :*/
/*::  latitude longitude are available at                        :*/
/*::  http://www.geodatasource.com                               :*/ 
/*::                                                             :*/
/*::  For enquiries, please contact [email protected]      :*/
/*::                                                             :*/
/*::  Official Web site: http://www.geodatasource.com            :*/
/*::                                                             :*/
/*::         GeoDataSource.com (C) All Rights Reserved 2014      :*/
/*::                                                             :*/
/*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/

function distance(lat1, lon1, lat2, lon2, unit) 
{
	var radlat1 = Math.PI * lat1/180;
	var radlat2 = Math.PI * lat2/180;
	var radlon1 = Math.PI * lon1/180;
	var radlon2 = Math.PI * lon2/180;
	var theta = lon1-lon2;
	var radtheta = Math.PI * theta/180;

	var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);

	dist = Math.acos(dist);
	dist = dist * 180/Math.PI;
	dist = dist * 60 * 1.1515;
	if (unit=="K") { dist = dist * 1.609344 }
	if (unit=="N") { dist = dist * 0.8684 }
	return dist;
}        

document.write(distance(32.9697, -96.80322, 29.46786, -98.53506, "K") + " Kilometers");
          

Distance between two Latitudes and Longitudes – Part 1

This series is about code in various languages that will calculate the distance between two latitudes and longitudes. This article is for the PHP code.

Code courtsey : GeoDataSource

/*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*::                                                             :*/
/*::  This routine calculates the distance between two           :*/
/*::  points (given the latitude/longitude of those points).     :*/
/*::  It is being used to calculate the distance between two     :*/
/*::  locations using GeoDataSource(TM) Products                 :*/
/*::                                                             :*/
/*::  Definitions:                                               :*/
/*::    South latitudes are negative,                            :*/
/*::    east longitudes are positive                             :*/
/*::                                                             :*/
/*::  Passed to function:                                        :*/
/*::    lat1, lon1 = Latitude and Longitude of point 1           :*/
/*::                 (in decimal degrees)                        :*/
/*::    lat2, lon2 = Latitude and Longitude of point 2           :*/
/*::                 (in decimal degrees)                        :*/
/*::    unit = the unit you desire for results                   :*/
/*::           where: 'M' is statute miles                       :*/
/*::                  'K' is kilometers (default)                :*/
/*::                  'N' is nautical miles                      :*/
/*::  Worldwide cities and other features databases with         :*/
/*::  latitude longitude are available at                        :*/
/*::  http://www.geodatasource.com                               :*/ 
/*::                                                             :*/
/*::  For enquiries, please contact [email protected]      :*/
/*::                                                             :*/
/*::  Official Web site: http://www.geodatasource.com            :*/
/*::                                                             :*/
/*::         GeoDataSource.com (C) All Rights Reserved 2014      :*/
/*::                                                             :*/
/*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/

function distance($lat1, $lon1, $lat2, $lon2, $unit) {

  $theta = $lon1 - $lon2;
  
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  
  $dist = acos($dist);
  $dist = rad2deg($dist);
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") 
  {
    return ($miles * 1.609344);
  } 
  else 
  	if ($unit == "N") 
  	{
     	  return ($miles * 0.8684);
   	} 
    else 
    {
        return $miles;
    }
}

echo distance(32.9697, -96.80322, 29.46786, -98.53506, "M") . " Miles
"; echo distance(32.9697, -96.80322, 29.46786, -98.53506, "K") . " Kilometers
"; echo distance(32.9697, -96.80322, 29.46786, -98.53506, "N") . " Nautical Miles
";

Simulating a form submit using POST method through CURL

Below piece of code can simulate a form submission through post method.

/******** The below header simulates Chrome Browser ********/

$header[0] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";

$header[1] = "Accept-Language: en-US,en;q=0.8"; 
$header[2] = "Cache-Control: max-age=0";
$header[3] = "Connection: keep-alive";
$header[4] = "Host: www.doamin-name.com";

$header[5] = "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36";

$header[6] = "Referer: http://www.referrer-domain.com/"; 

/***********  end of header **********************/


$url = "http://www.doamin-name.com/page.php";
$param = "param=value1&submit=Submit"; // params that need to be passed
       
$ch = curl_init() or die(curl_error()); 
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 

//curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); // would be required if the return is going to be a binary file like image. From PHP ver 5.1.3 onwards the return is always binary so need not set this if PHP ver is >= 5.1.3

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //returns the received data in a variable. Must be on if CURLOPT_BINARYTRANSFER is set to 1 or true

//curl_setopt($ch, CURLOPT_COOKIE, 'PHPSESSID=' . $_COOKIE['PHPSESSID']); // if required. This sets Cookies to be sent with the request

$data1=curl_exec($ch) or die(curl_error($ch));
curl_close($ch);

If PHP Session Cookie needs to be retrieved from the result of the above request:

preg_match('/^Set-Cookie:\s*([^;]*)/mi', $data1, $m);
parse_str($m[1], $cookies);

echo $cookies['PHPSESSID'];

Database of All Countries

Here is a MySQL dump of all the countries in one table. It is a pretty handy database with 2 char country codes, 3 char country codes and latitude and longitude (somewhat in the middle area) of each countries. Below are the columns of the table.
Country Table Structure

And below is a sample of the data stored in each row.
country-row-sample

Here is the link for downloading the dump file country.sql
Let me know if other formats like CSV or XML will be more helpful.

Image Cropping in PHP – Part 2

Here is the second part of the article “Image Cropping in PHP”. The first part is here

This part describes the function imagecrop introduced in PHP 5.5.0 for cropping images. imagecrop can be used to crop an image based on a start and end point/co-ordinate and dimensions. (It doesn’t take into account any color like imagecropauto )
It is a relatively simpler and easier to use.

Syntax:
$resource imagecrop ( resource $image , array $rect )
Parameters:

$image
resource returned by any create image function like imagecreatefromjpeg or imagecreatetruecolor etc.

$rect
This will be an array that will hold the x, y co-ordinate and the dimensions. This will define the rectangular area of the image that will be kept.
The array keys must be “x”, “y”, “width” and “height”.

For example in the below image the light green border needs to be removed, so the rect will be array(“x”=>27, “y”=>26, “width”=>163, “height”=>142) (the values might not be pixel perfect – it is just for demonstration)
imagecrop1

Example Code:
....
$image_src = imagecreatefrompng($_FILES['image']['tmp_name']);

$croppedImage = imagecrop($image_src,array("x"=>27,"y"=>26,"width"=>163,"height"=>142));
 
header( 'Content-Type: image/png');

imagepng($croppedImage);

Below left is the original image and right is the cropped image (using the above example).

Untitled2

final2

 

Image Cropping in PHP – Part 1

With PHP 5.5.0 two functions, imagecropauto and imagecrop, have been added for advanced image resizing. This article describes the imagecropauto function.

The imagecropauto function is useful to remove borders or background/outer area of a photo. The mode parameter defines the border to be removed e.g. IMG_CROP_BLACK will remove black borders, IMG_CROP_WHITE will remove white borders etc.
Multicolored borders can be also be removed using the IMG_CROP_THRESHOLD mode, though it will be a bit tricky — couldn’t yet find a calculator to calculate the value of threshold.

Syntax:
resource imagecropauto ( resource $image [, int $mode = -1 [, float $threshold = .5 [, int $color = -1 ]]] )
Parameters:

$image
resource returned by any create image function like imagecreatefromjpeg or imagecreatetruecolor etc.

$modes
IMG_CROP_TRANSPARENT / IMG_CROP_BLACK / IMG_CROP_WHITE / IMG_CROP_SIDES / IMG_CROP_THRESHOLD / IMG_CROP_DEFAULT

$threshold
Applicable if IMG_CROP_THRESHOLD is used in mode. The value is based on the color distance in the RGB cube model.

$color
This code can be derived by converting the HEX value (of a color) to decimal value.

Example Code:
....
$image_src = imagecreatefrompng($_FILES['image']['tmp_name']);

$croppedImage = imagecropauto($image_src,IMG_CROP_THRESHOLD,27.8,10746029);
 
header( 'Content-Type: image/png');

imagepng($croppedImage);

In the above code 10746029 decimal is equivalent to A3F8AD Hex – the outermost light green color in the below test image.
Below left is the original image and right is the cropped image (using the above example).

Untitled2

Untitled

 
 

Here is the second part of this article.

Some Useful Regex

Mail-id verification:

/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/

Though both can be used in PHP and JS but there is another method to verify an email-id in PHP, by using the below code

if(!filter_var($email, FILTER_VALIDATE_EMAIL))

FILTER_VALIDATE_EMAIL is a predefined filter in PHP.
Name Verification:

/^[A-Za-z .'-]+$/

Phone Verification:

/^[0-9 -]+$/

Removing all spaces:

$pattern = '/\s+/';
$replace = "";
$string = preg_replace($pattern,$replace,$string);

 

Secure Upload Folders

There are two ways to prevent execution of any (malicious) scripts uploaded to by users.
Method one – like described in this post.
Method two – add the below code to .htaccess file of the directory that needs to be protected.

RemoveHandler .cgi .php .php3 .php4 .php5 .phtml .pl .py .pyc .pyo .sh .html .shtml .jsp

If it doesn’t work for PHP scripts on servers where suPHP is enabled, then see this post