All posts by Manish

PayPal form submit through PHP

PayPal Payments Standard is a quick and easy way to integrate Paypal with any website. Normally the method uses a form to send the various details of the transaction to Paypal server.

The below code can simulate the form submission through PHP. With this no form is required. The details of transaction pulled from DB, calculations (if any) done through PHP code and the user can be redirected to Paypal for making the payment.

 
$paypal_url = 'https://www.paypal.com/cgi-bin/webscr';
$paypal_id = 'XXXXXXXXXX'; // Paypal Merchant Id
$cancel_url = "http://www.domain.com/cancel-return.php";
$return_url = "http://www.domain.com/success-return.php"; 
$inv = "INV/BVRM/".rand(1111,9999);
        
// Prepare GET data
$query = array();
$query['notify_url'] = "http://www.domain.com/ipn.php";
$query['cmd'] = '_xclick';
$query['business'] = $paypal_id;
//$query['address_override'] = '1';
$query['first_name'] = "John Doe";
$query['country'] = "IN";
$query['email'] = $_SESSION['email'];
$query['amount'] = $product_details['price'];
$query['item_name'] = $product_details['name'];
$query['currency_code'] = "INR";

$query['custom'] = $_SESSION['user_id'] . "," . $package_price . "," . $package_validity . "," . $package_name;

$query['return'] = $return_url;
$query['cancel_return'] = $cancel_url;
$query['rm'] = "2";
$query['invoice'] = $inv;
    
// Prepare query string
$query_string = http_build_query($query);

header('location: ' . $paypal_url. "?". $query_string);
die();

The array keys are the names of the various fields of the form that is used normally in PayPal Payments Standard method. A detail of all available parameters/fields can be found here

Distance between two Latitudes and Longitudes – Part 3

This series is about code in various languages that will calculate the distance between two latitudes and longitudes. This article is for the C 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      :*/
/*::                                                             :*/
/*::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/

#include 

#define pi 3.14159265358979323846

double distance(double lat1, double lon1, double lat2, double lon2, char unit) 
{
  double theta, dist;
  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);
  dist = dist * 60 * 1.1515;
  switch(unit) 
 {
    case 'M':
      break;
    case 'K':
      dist = dist * 1.609344;
      break;
    case 'N':
      dist = dist * 0.8684;
      break;
  }
  return (dist);
}

/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*::  This function converts decimal degrees to radians             :*/
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
double deg2rad(double deg) {
  return (deg * pi / 180);
}

/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*::  This function converts radians to decimal degrees             :*/
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
double rad2deg(double rad) {
  return (rad * 180 / pi);
}

printf("%f",distance(32.9697, -96.80322, 29.46786, -98.53506, "K"));
puts(" Kilometers");

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.