Pixel Envision Ltd.
Indie Game Development Studio
  • Home
  • About Us
    • Privacy Policy
    • Press Kit
  • Our Games
    • Casual Games
      • Hordes of Enemies
      • noded
      • kubic
      • Whip Swing
      • Witches’ Brew
    • Kids Apps
      • Cars & Trucks Puzzle
      • Train Puzzles for Kids
      • Animal Puzzle
      • Fairy Tale Puzzles for Kids
      • Coloring Book
      • Find the Differences
  • Blog
  • Support
Select Page ...

Tag: PHP

PHP Credit Card Validation class using Mod 10 (Luhn) + more!

February 17, 2012 PHP, Programming

Here is another PHP code snippet from my library. This PHP class allows you to validate credit card information before processing it further. Doing all possible off-line checks before sending it to he credit card gateway will help you save time & money…

If the card is valid it will return cleaned & formatted card number along with the card type (Visa, Mastercard, Amex, Dinners, Discover, JCB & Maestro).

Besides regular checks, validates the card number against Mod 10 (Luhn) as well as know test card numbers…

Features

  • Checks if the card number, expiration date & validation numbers are valid.
  • Checks if the card is expired
  • Finds & returns the card type.
  • Checks against the known test card numbers.
  • Validates the card number using Mod 10 algorithm.

Usage Sample

<?php
require('mod10.php');
$CARDTYPE=$ErrArr=NULL;

$cc = new CCVal($_POST["card_number"], $_POST["card_expire_month"], $_POST["card_expire_year"], $_POST["card_cvv2"]);

$cstatus=$cc->IsValid();

	if($cstatus[0]=="valid") {
		$CARDTYPE=$cstatus[1];
		$_POST["card_number"]=$cstatus[2];
		$_POST["card_cvv2"]=$cstatus[3];
	}else {
		$ErrArr=$cstatus;
	}

?>

Download

  • Download PHP code snippet *UPDATED FOR AMEX CVV FIX
  • Code is PHP5 compatible but it should also work on PHP4 (Untested)

License

This code is free to use, distribute, modify and study. When referencing please link back to this website / post in any way e.g. direct link, credits etc. If you find this useful, please leave a comment and share using the buttons below!
__ccNum = $cardNumber; 
	  } 
	} 

	if(!empty($cvv)) 
	{ 
	  $cardCVV = ereg_replace("[^0-9]", "", $cvv); 
	  if(!empty($cardCVV)) 
	  { 
		$this->__ccCVV = $cardCVV; 
	  } 
	} 

	if(!is_numeric($expm) || $expm < 1 || $expm > 12) 
	{ 
	  $this->__ccExpM =NULL;
	} 
	else 
	{ 
	  $this->__ccExpM = $expm; 
	} 

	$currentYear = date('Y');
	settype($currentYear, 'integer');
	$expy=$expy+2000;
	if(!is_numeric($expy) || $expy < $currentYear || $expy > $currentYear + 15) 
	{ 
	  $this->__ccExpY = NULL; 
	} 
	else 
	{ 
	  $this->__ccExpY = $expy; 
	}

	if (ereg("^5[1-5][0-9]{14}$", $this->__ccNum)) {
		$this->__ccType = MASTERCARD;}
	elseif (ereg("^4[0-9]{12}([0-9]{3})?$", $this->__ccNum)) {
		$this->__ccType = VISA;}
	elseif (ereg("^3[47][0-9]{13}$", $this->__ccNum)) {
		$this->__ccType = AMEX;}
	elseif (ereg("^3(0[0-5]|[68][0-9])[0-9]{11}$", $this->__ccNum)) {
		$this->__ccType = DINNERS;}
	elseif (ereg("^6011[0-9]{12}$", $this->__ccNum)) {
		$this->__ccType = DISCOVER;}
	elseif (ereg("^(3[0-9]{4}|2131|1800)[0-9]{11}$", $this->__ccNum)) {
		$this->__ccType = JCB;}
	elseif (ereg("^(5[06-8]|6)[0-9]{10,17}$", $this->__ccNum)) {
		$this->__ccType = MAESTRO;}
	else {
		$this->__ccType = UNKNOWN;}
}

function IsValid() 
{ 

  $validFormat = false; 
  $validExp = false;
  $passCheck = false;
  $validCVV = false;
  $testCard = false;

switch($this->__ccType) 
{ 
  case MASTERCARD: 
    $validFormat = true;
    break; 
case VISA: 
    $validFormat = true;
    break; 
case AMEX: 
    $validFormat = true;
    break; 
case DISCOVER: 
    $validFormat = true;
    break; 
case DINNERS: 
    $validFormat = true;
    break; 
case JCB: 
    $validFormat = true; 
    break; 
case MAESTRO: 
    $validFormat = true; 
    break; 
  default: 

  $validFormat = false; 
}

$cardExpM = $this->__ccExpM; 
$cardExpY = $this->__ccExpY;

if($cardExpM && $cardExpY && date('Ym')<=$cardExpY.$cardExpM) {
$validExp = true;
}

$cardCVV = $this->__ccCVV; 

if($cardCVV && (strlen($cardCVV)==3 && $this->__ccType!=AMEX)) {
$validCVV = true;
} elseif($cardCVV && (strlen($cardCVV)==4 && $this->__ccType==AMEX)) {
$validCVV = true;
}

$cardNumber = strrev($this->__ccNum); 
$numSum = 0; 

for($i = 0; $i < strlen($cardNumber); $i++) 
{ 
  $currentNum = substr($cardNumber, $i, 1); 

if($i % 2 == 1) 
{ 
  $currentNum *= 2; 
} 

if($currentNum > 9) 
{ 
  $firstNum = $currentNum % 10; 
  $secondNum = ($currentNum - $firstNum) / 10; 
  $currentNum = $firstNum + $secondNum; 
} 

$numSum += $currentNum; 
}

$passCheck = ($numSum % 10 == 0);

$testCard = in_array($this->__ccNum,array('340000000000009','341111111111111','343434343434343','346827630435344','370000000000002','370000200000000','370407269909809','370556019309221','371449635398431','374200000000004','376462280921451','377752749896404','378282246310005','378734493671000','30000000000004','30569309025904','5019717010103742','30204169322643','30218047196557','30221511563252','36000000000008','36148900647913','36700102000000','38000000000006','38520000023237','6011000000000004','6011000000000012','6011000400000000','6011000990139424','6011111111111117','6011153216371980','6011601160116611','6011687482564166','6011814836905651','201400000000009','201481123699422','214925980592653','214983972181233','180001638277392','180040153546898','180058601526635','3528000700000000','3528723740022896','3530111333300000','3566002020360505','3569990000000009','630495060000000000','6304900017740292441','6333333333333333336','5100080000000000','5105105105105100','5111111111111118','5123619745395853','5138495125550554','5274576394259961','5301745529138831','5311531286000465','5364587011785834','5404000000000001','5424000000000015','5431111111111111','5454545454545454','5459886265631843','5460506048039935','5500000000000004','5500939178004613','5555555555554444','5565552064481449','5597507644910558','6334580500000000','6334900000000005','633473060000000000','6767622222222222222','6767676767676767671','5641820000000005','6331101999990016','6759649826438453','4007000000027','4012888818888','4024007127653','4222222222222','4556069275201','4556381812806','4911830000000','4916183935082','4916603452528','4929000000006','4005550000000019','4012888888881881','4111111111111111','4444333322221111','4539105011539664','4544182174537267','4716914706534228','4916541713757159','4916615639346972','4917610000000000','4406080400000000','4462000000000003','4462030000000000','4917300000000008','4917300800000000','4484070000000000','4485680502719433'));

  if($validFormat && $validExp && $validCVV && $passCheck && !$testCard) {
	  return array("valid",$this->__ccType,$this->__ccNum,$this->__ccCVV);
  } else {
  $ERR=NULL;
  if(!$validFormat || !$passCheck) $ERR[]="Invalid card number";
  if(!$validCVV) $ERR[]="Invalid CVV2/CVC2 Number";
  if(!$validExp) $ERR[]="Credit card has been expired";  
  if($testCard) $ERR[]="Reserved card number";
  return $ERR;
  }
 } 
} 
?>

How I integrated osTicket to WordPress

September 7, 2011 PHP, Tips & Tricks

I’ve been looking for ways to provide a proper customer support for our website & products. Of course, just giving out your support email could also do it, but I wanted to have centralized on-line solution which makes things easier on both sides of a support request.

After looking for options (of course there are better paid alternatives), I have decided to use osTicket, which is a widely-used open source support ticket system. osTicket also supports email piping, so customers can submit new support request simply by sending an email to us. Email piping support was one of the key factors for my decision.

osTicket Bugs & Fixes

While working on the integration, I’ve noticed few bugs in the osTicket (v1.6.0 Stable) that needs to be fixed for a proper operation.

Captcha Image Problem

After the installation & setup of osTicket I have noticed captcha images are not shown properly. Most of the major browsers were failing to show captcha image by displaying the red X instead. In order to fix that problem you have to edit following file located in “include” subfolder.

class.captcha.php

Edit that file and look for the line #48 and change it as follows:

//Original
Header ("(captcha-content-type:) image/png");

//Fixed
Header ("Content-Type: image/png");

Captcha Validation Problem

When trying out the system, I have noticed submitting a new ticket is not possible for logged in users. Captcha image is not shown for logged in users (which is a proper thing to do) and when the new ticket is submitted, validation fails. In order to fix that problem you have to edit following file located in the root folder. Thanks to rayflexcom @ osTicket forum for the original fix.

open.php

Edit that file and look for the line #23 and change it as follows:

//Original
        if(!$thisuser && $cfg->enableCaptcha()){ 
            if(!$_POST['captcha']) 
                $errors['captcha']='Enter text shown on the image'; 
            elseif(strcmp($_SESSION['captcha'],md5($_POST['captcha']))) 
                $errors['captcha']='Invalid - try again!'; 
        }

//Fixed
    if($thisclient && $thisclient->getId() && $thisclient->isValid()){ 
    }else{ 
        if(!$thisuser && $cfg->enableCaptcha()){ 
            if(!$_POST['captcha']) 
                $errors['captcha']='Enter text shown on the image'; 
            elseif(strcmp($_SESSION['captcha'],md5($_POST['captcha']))) 
                $errors['captcha']='Invalid - try again!'; 
        } 
    }

Embed osTicket to your WordPress Template

Initial integration is fairly easy, but to fully embed it into your template you should edit the html/css code in php files.

Base Setup

Locate the following file located in the root folder. This is a bit different than the other methods you can find on internet.

First of all, it checks for the current folder. If the request is coming from the osTicket’s default admin folder (scp) it won’t load the WordPress template. Without that line, osTicket admin pages will be broken hybrid of it’s own design and your template.

Second, if you are using WordPress permalinks like I do, sub-pages (contact/index.php, contact/open.php, etc.) will return header section of your WordPress 404 page. osTicket will work but that will not be very SEO friendly. Just change “/contact/” to match your setup (osticket, support, etc.)

main.inc.php

Edit that file and look for the line #99 (with the other includes and requires which you can find under the line that reads “#include required files”) and add the following code:

//Original
if (!strpos($_SERVER["SCRIPT_FILENAME"], "/scp/")) {
    $_SERVER["REQUEST_URI"]="/contact/";
    include(ROOT_DIR.'../wp-blog-header.php');
}

Template Integration

Edit following files located in the “include/client/” subfolder.

header.inc.php
footer.inc.php

Edit both files and change them as follows:

//header.inc.php
//Add this to the top of the file
get_header();
//Keep the original html menu code starting with <div id="container">

//footer.inc.php
//Add this after the closing div tag for container </div>
get_footer();

For rest of the changes you should check the files on root folder & “include/client/” folder and edit html/css code to match your template.

You can see the live version of my integration by visiting our “support” page.

If you find this useful, please leave a comment and share using the buttons below!

PHP Currency Converter

August 18, 2011 PHP, Programming

Here is another PHP code snippet from my library. This PHP function allows you to calculate exchange amounts between 49 countries and 33 currencies.

Function is based on the live conversion reference rates provided by European Central Bank.

Usage

  • First 3 parameters are required. First one is the origin currency and the second one is target currency.
  • First 2 parameters should be the same type. If you are doing a county code based conversion both must be country codes. If you are doing currency code based conversion, both should be currency codes.
  • 3rd parameter is the amount you want to be converted. Should be decimal digits without any currency signs or codes attached to it.
  • 4th parameter is optional and set as true by default. When enabled function will prepend or append the currency sign (or code) to the output amount. You may want to turn that off if you will use the returned amount in a calculation.
  • 5th and the last parameter is calculation precision. Controls the number of digits after the decimal point. Default is 5.

Usage Samples

  • currency_convert(“EUR”,”USD”,100)
  • currency_convert(“FR”,”GB”,98);
  • currency_convert(“AUD”,”CNY”,145,false,8);
  • currency_convert(“GR”,”DK”,3500,true,2);

Download

  • Download PHP code snippet
  • Code is PHP5 compatible but it should also work on PHP4 (Untested)

License

This code is free to use, distribute, modify and study. When referencing please link back to this website / post in any way e.g. direct link, credits etc. If you find this useful, please leave a comment and share using the buttons below!
<?php
// Realtime currency converter by Pixel Envision (E.Gonenc)
// Version 1.0 - 18 August 2011
// Based on the live conversion reference rates provided by European Central Bank
// http://www.ecb.europa.eu/

function currency_convert($from,$to,$amount,$sign=true,$sensitivity=5) {
$RATES=$BASE=$in=$out=$append=NULL;

//Array of available countries & currencies
$CURRENCY=array("US"=>"USD","BE"=>"EUR","ES"=>"EUR","LU"=>"EUR","PT"=>"EUR","DE"=>"EUR","FR"=>"EUR","MT"=>"EUR","SI"=>"EUR","IE"=>"EUR","IT"=>"EUR","NL"=>"EUR","SK"=>"EUR","GR"=>"EUR","CY"=>"EUR","AT"=>"EUR","FI"=>"EUR","JP"=>"JPY","BG"=>"BGN","CZ"=>"CZK","DK"=>"DKK","EE"=>"EEK","GB"=>"GBP","HU"=>"HUF","LT"=>"LTL","LV"=>"LVL","PL"=>"PLN","RO"=>"RON","SE"=>"SEK","CH"=>"CHF","NO"=>"NOK","HR"=>"HRK","RU"=>"RUB","TR"=>"TRY","AU"=>"AUD","BR"=>"BRL","CA"=>"CAD","CN"=>"CNY","HK"=>"HKD","ID"=>"IDR","IN"=>"INR","KR"=>"KRW","MX"=>"MXN","MY"=>"MYR","NZ"=>"NZD","PH"=>"PHP","SG"=>"SGD","TH"=>"THB","ZA"=>"ZAR");

if (strlen($from)==2 && strlen($to)==2) {//Operate using country code
	if(isset($CURRENCY[$from])) {$in=$CURRENCY[$from];}
	if(isset($CURRENCY[$to])) {$out=$CURRENCY[$to];}
} elseif (strlen($from)==3 && strlen($to)==3) {//Operate using currency code
	if(in_array($from,$CURRENCY)) {$in=$from;}
	if(in_array($to,$CURRENCY)) {$out=$to;}
} else {
	echo "Error: You should either use 2 digit country codes or 3 digit currency codes!";
}

	if ($in && $out) {//Both currencies available, continue
	
		//Load live conversion rates and set as an array
		$XMLContent= file("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");		
		if(is_array($XMLContent)) {
			foreach ($XMLContent as $line) {
					if (ereg("currency='([[:alpha:]]+)'",$line,$currencyCode)) {
						if (ereg("rate='([[:graph:]]+)'",$line,$rate)) {
								$RATES[$currencyCode[1]]=$rate[1];
						}
					}
			}
		}
		if(is_array($RATES)) {
			
		$RATES["EUR"]=1; //Add EUR reference to array
		if ($in!="EUR") {//Normalize rate to given input
		$BASE=$RATES[$in];
		foreach ($RATES as $code => $rate) {
			$RATES[$code]=round($rate/$BASE,$sensitivity);}
		}

		//Prepend or append the currency information
		if ($sign) {
			if ($out=="USD") {echo "$";}
			elseif ($out=="EUR") {echo "&euro;";}
			elseif ($out=="GBP") {echo "&pound;";}
			elseif ($out=="JPY") {echo "&yen;";}
			else {$append=$out;}
		}
		
		echo round($amount*$RATES[$out],$sensitivity);//Output the converted amount
		
		if ($append) {echo " ".$append;}

		} else {
			echo "Error: Unable to load conversion rates!";	
		}
	
	} else {
		echo "Error: Either one or both of given currencies are not available for conversion!";	
	}
}

echo currency_convert("EUR","USD",1);
?>

Finding visitors real IP using PHP

August 16, 2011 PHP, Programming

Third PHP snippet I’m sharing from my library is code that tries to get most accurate real IP of the visitor. There are few headers with the IP information but those can be populated with many different ip’s based on customers route to your server. This script evolved in time and I believe it returns a very accurate source IP based on the information given in the request headers. But if you find a bug or a way to enhance it more, let me know!

License

This code is free to use, distribute, modify and study. When referencing please link back to this website / post in any way e.g. direct link, credits etc. If you find this useful, please leave a comment and share using the buttons below!
<?php
function realip() {

	$ip=trim($_SERVER['REMOTE_ADDR']);

	if($_SERVER["HTTP_CLIENT_IP"]) {

		if(preg_match( "~\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}~",trim($_SERVER["HTTP_CLIENT_IP"])) && !preg_match( "~^((0|10|127|169\.254|172\.(1[6-9]|2[0-9]|3[0-1])|192\.0\.2|192\.168|255\.255\.255)\.)~",trim($_SERVER["HTTP_CLIENT_IP"]))) {$ip=trim($_SERVER["HTTP_CLIENT_IP"]);}	

	} elseif ($_SERVER["HTTP_X_FORWARDED_FOR"]) {

		foreach (explode(",",$_SERVER["HTTP_X_FORWARDED_FOR"]) as $key) {

			if(preg_match( "~\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}~",trim($key)) && !preg_match( "~^((0|10|127|169\.254|172\.(1[6-9]|2[0-9]|3[0-1])|192\.0\.2|192\.168|255\.255\.255)\.)~",trim($key))) {$ip=trim($key);break;}

		}

	}
return($ip);
}

$IP=realip();
?>

PHP e-mail validation code snippet

August 15, 2011 PHP, Programming

Validation of email

This is the second PHP snippet I’m sharing from my library. It is not very complicated but get’s the job done. It both checks for the email syntax (REGEX) and existence of the email domain by checking MX & A records…

License

This code is free to use, distribute, modify and study. When referencing please link back to this website / post in any way e.g. direct link, credits etc. If you find this useful, please leave a comment and share using the buttons below!
<?php
$email="test@domain.com";

if (!preg_match("/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)*\.\w{2,8}$/i",$email)){

	//E-mail syntax is invalid

} elseif(!checkdnsrr(array_pop( explode("@",$email) ), "MX" ) &amp;&amp; !checkdnsrr(array_pop( explode("@",$email) ), "A" )) {

	//Email server is not valid

} else {

	//E-mail is valid

}
?>

ZIP (POSTAL) Code Validation Regex & PHP code for 12 Countries

August 14, 2011 PHP, Programming

For the last couple of years, I’ve been mostly doing PHP coding. As a result, I have small library of code snippets of my own. Those are simple but useful PHP codes that might save some time on your work!

First one I’m sharing here today is the combination of regular expression and the PHP code to do ZIP code (or Postal Code) validation for following 12 countries: United States of America, United Kingdom, Germany, Canada, France, Italy, Australia, Netherlands, Spain, Denmark, Sweden & Belgium.

Code is provided in PHP but the REGEX codes are universal and those can be used with other programming languages.

License

This code is free to use, distribute, modify and study. When referencing please link back to this website / post in any way e.g. direct link, credits etc. If you find this useful, please leave a comment and share using the buttons below!
<?php
$country_code="US";
$zip_postal="11111";

$ZIPREG=array(
	"US"=>"^\d{5}([\-]?\d{4})?$",
	"UK"=>"^(GIR|[A-Z]\d[A-Z\d]??|[A-Z]{2}\d[A-Z\d]??)[ ]??(\d[A-Z]{2})$",
	"DE"=>"\b((?:0[1-46-9]\d{3})|(?:[1-357-9]\d{4})|(?:[4][0-24-9]\d{3})|(?:[6][013-9]\d{3}))\b",
	"CA"=>"^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$",
	"FR"=>"^(F-)?((2[A|B])|[0-9]{2})[0-9]{3}$",
	"IT"=>"^(V-|I-)?[0-9]{5}$",
	"AU"=>"^(0[289][0-9]{2})|([1345689][0-9]{3})|(2[0-8][0-9]{2})|(290[0-9])|(291[0-4])|(7[0-4][0-9]{2})|(7[8-9][0-9]{2})$",
	"NL"=>"^[1-9][0-9]{3}\s?([a-zA-Z]{2})?$",
	"ES"=>"^([1-9]{2}|[0-9][1-9]|[1-9][0-9])[0-9]{3}$",
	"DK"=>"^([D-d][K-k])?( |-)?[1-9]{1}[0-9]{3}$",
	"SE"=>"^(s-|S-){0,1}[0-9]{3}\s?[0-9]{2}$",
	"BE"=>"^[1-9]{1}[0-9]{3}$"
);

if ($ZIPREG[$country_code]) {

	if (!preg_match("/".$ZIPREG[$country_code]."/i",$zip_postal)){
		//Validation failed, provided zip/postal code is not valid.
	} else {
		//Validation passed, provided zip/postal code is valid.
	}

} else {

	//Validation not available

}
?>
12»
  • Tweets by PixelEnvision

  • Recent Comments

    • Yogesh Singh on ZIP (POSTAL) Code Validation Regex & PHP code for 12 Countries
    • Admin on Maxscript – Vray Cubemap Generator for Unity
    • charlie on Maxscript – Vray Cubemap Generator for Unity
    • Mastan on PHP Currency Converter
    • Rakesh Vishnoi on ZIP (POSTAL) Code Validation Regex & PHP code for 12 Countries
  • Tags

    Coming Soon CoronaSDK Featured Flash Lua PHP Programming Reviews Tips & Tricks Unity 3D Windows Phone
    • Find us on

      amazonandroidapplefacebooklinkedinrsstwitterwindowsyoutube
    • Company Information

      Pixel Envision Limited is a company registered in England, company number: 09558675. Registered Office: Preston Park House, South Road, Brighton, East Sussex, BN1 6SB, United Kingdom

    • Press Kit
    • Privacy Policy
    Copyright © 2011-2018 Pixel Envision Ltd, all rights reserved.
    We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.OKNoPrivacy policy
    Revoke cookies