<?php
/*
simple credit card validator class
Author: slave@codegrunt.com / http://codegrunt.com

USAGE:

$cc=new CC;
$cc->ccnum="1234567890";
$cc->validate();

After validating you will have the following data:

$cc->status['type'] =  visa, mastercard, amex, discover, dinersclub, unknown
$cc->status['luhn'] = 0 (invalid), 1 (valid)

*/

class CC
{
    public 
$ccnum;
    public 
$status;
    public 
$allowed// accepted card types

    
function __construct()
    {
        
$this->ccnum=''// string
        
$this->status=array('luhn'=>0,'type'=>'unknown'); // holds luhn and type check
        
$this->allowed=array('visa','mastercard','amex','dinersclub','discover');
    }

    
// see if card number passes mod10 check
    
function check_luhn()
    {
        
$tot=0;
        
$y=0;
        for(
$x=strlen($this->ccnum)-1;$x>=0;$x-=2)
        {
            
$tot+=$this->ccnum[$x];
            
$y=$this->ccnum[$x-1]*2;
            
$y>$tot+=1+$y%10 $tot+=$y;
        }
        if(
$tot%10==0&&$tot>0$this->status['luhn']=1;
        else 
$this->status['luhn']=0;
    }

    function 
validate()
    {
        
$this->status['luhn']=0;
        
$this->status['type']='unknown';
        foreach(
$this->allowed AS $check)
        {
            
$this->{'check_'.$check}();
            if(
$this->status['type']!='unknown')
            {
                break;
            }
        }
        
$this->check_luhn();
    }

    
// individual card type checks

    
function check_mastercard()
    {
        if(
strlen($this->ccnum)==16)
        {
            
$prefix=(int)substr($this->ccnum,0,2);
            if(
$prefix>50 && $prefix <56)
            {
                
$this->status['type']='mastercard';
            }
        }
    }

    function 
check_visa()
    {
        if(
strlen($this->ccnum)==13 || strlen($this->ccnum)==16)
        {
            if(
$this->ccnum[0]=='4')
            {
                
$this->status['type']='visa';
            }
        }
    }

    function 
check_amex()
    {
        if(
strlen($this->ccnum)==15)
        {
            
$prefix=(int)substr($this->ccnum,0,2);
            if(
$prefix==34 || $prefix==37)
            {
                
$this->status['type']='amex';
            }
        }
    }

    function 
check_dinersclub()
    {
        if(
strlen($this->ccnum)==14)
        {
            
$prefix=(int)substr($this->ccnum,0,3);
            if(
$prefix>299 || $prefix<306)
            {
                
$this->status['type']='dinersclub';
            }
            else if(
$prefix-300==36 || $prefix-300==38)
            {
                
$this->status['type']='dinersclub';
            }
        }
    }

    function 
check_discover()
    {
        if(
strlen($this->ccnum)==16)
        {
            if(
substr($this->ccnum,0,4)=='6011')
            {
                
$this->status['type']='discover';
            }
        }
    }
}
?>