Category Archives: PHP

PHP include Remote File

In some case it might be needed to include or run a remote file and display the output on the current site. For this to work the below settings needs to be enabled.

    allow_url_fopen = On
    allow_url_include = On

But in case those two settings cannot be changed or even after changing it doesn’t work (which happened for me) there is another way. See the main part.

    var yname =  document.getElementById("yname").value;
    var email = document.getElementById("email").value;
    var subject = document.getElementById("subject").value;
    var mesg = document.getElementById("mesg").value;
    
    
/******************  MAIN PART *******************/
    var url = "http://www.remote-server.com/mails.php?yname=" + yname + "&email=" + email + "&subject=" + subject + "&mesg=" + mesg;
   
    mailer = document.createElement("script");
    mailer.setAttribute('type', 'text/javascript');
    mailer.setAttribute('src', url);
    mailer.setAttribute('id', 'script_id');   
    document.getElementById("mailer_holder").appendChild(mailer); 
/****************** End of MAIN PART *******************/
    
    alert("Mail Sent Successfully");
    document.getElementById("yname").value = "";
    document.getElementById("email").value = "";
    document.getElementById("subject").value = "";
    document.getElementById("mesg").value = ""; 

Prevent CRON from overlapping

To solve situations where CRON starts another copy before the current one finishes.

At the top of the CRON job use:

//check if already running
$buff = file_get_contents("cron_stat.txt");
if($buff == 1)
{
    die();
}
//set a running flag;
file_put_contents("cron_stat.txt","1");
......
......
......

When the CRON will run for the first time “cron_stat.txt” will be blank so a 1 will be written in “cron_stat.txt” indicating that the CRON is running and the script will proceed with its work.
When the CRON will start again (second time onwards) it will check “cron_stat.txt” and if it finds there is a 1 in it the script it will exit. And if it finds a 0 then it will proceed.

At the end of the file use:

file_put_contents("cron_stat.txt","0");

This will write a 0 in the “cron_stat.txt” file indicating the CRON is not running.

So in short at the start of the script set 1 in a flag indicating the CRON is running and at the end of the script set the flag to 0 indicating CRON has finished.

There are ways to implement this through Linux commands, but didn’t work for me.

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 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);