《php 5 in practice中文版》里提供的信用卡验证示例

对《PHP 5 in practice中文版》里提供的信用卡验证PHP代码感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧!
商业站点需要处理信用卡号码。信用卡公司已经在卡号里建立了校验体系。在把信用卡号码标准化为不包含空格的数字字符串之后,可以进行两方面的检验。

首先,不同信用卡公司遵循特定的编号规则。
n visa:以4开头,共有13位或16位数字。
n mastercard:以51~56开头,共有16位数字。
n american express:以34或37开头,共有15位数字。
n discover:以6011开头,共有16位数字。

另外,所有卡号还要遵循称为“mod10”的算法,它可以用来判断某个号码是否属于有效的信用卡号码。它的工作方式是这样的:首先颠倒数字的次序,接着每隔一个数字把数字乘以2,然后把所有的数字加起来;但如果相乘结果大于等于10,就要把这个结果的个位和十位的数字加起来。例如数字7,乘以2以后是14,所以它对应的数字应该是1+4=5。在所有数字相加之后,其结果应该能够被10整除。上述这些规则都写入了程序清单11.5.1包含的函数里。

程序清单11.5.1信用卡号码函数

/**
 * 《PHP 5 in practice中文版》里提供的信用卡验证PHP代码
 *
 * @param 
 * @arrange 512-笔记网: www.jb51.cc
 **/
<?PHP
//afunctionthatwillacceptandcleanupccnumbers
functionstandardize_credit($num){
//removeallnon-digitsfromthestring
returnpreg_replace('/[^0-9]/','',$num);
}
//afunctiontocheckthevalidityofaccnumber
//itmustbeprovidedwiththenumberitself,aswellas
//acharacterspecifyingthetypeofcc:
//m=mastercard,v=visa,d=discover,a=americanexpress
functionvalidate_credit($num,$type){
//firstperformtheccspecifictests:
//storeafewevaluationswewillneedoften:
$len=strlen($num);
$d2=substr($num,2);
//ifvisamuststartwitha4,andbe13or16digitslong:
if((($type=='v')&&(($num{0}!=4)||
!(($len==13)||($len==16))))||
//ifmastercard,startwith51-56,andbe16digitslong:
(($type=='m')&&(($d2<51)||
($d2>56)||($len!=16)))||
//ifamericanexpress,startwith34or37,15digitslong:
(($type=='a')&&(!(($d2==34)||
($d2==37))||($len!=15)))||
//ifdiscover:startwith6011and16digitslong
(($type=='d')&&((substr($num,4)!=6011)||
($len!=16)))){
//invalidcard:
returnfalse;
}
//ifwearestillhere,thentimetomanipulateanddothemod10
//algorithm.firstbreakthenumberintoanarrayofcharacters:
$digits=str_split($num);
//Nowreverseit:
$digits=array_reverse($digits);
//doubleeveryotherdigit:
foreach(range(1,count($digits)-1,2)as$x){
//doubleit
$digits[$x]*=2;
//ifthisisNowover10,goaheadandadditsdigits,easiersince
//thefirstdigitwillalwaysbe1
if($digits[$x]>9){
$digits[$x]=($digits[$x]-10)+1;
}
}
//Now,addallthisvaluestogethertogetthechecksum
$checksum=array_sum($digits);
//ifthiswasdivisibleby10,thentrue,elseit'sinvalid
return(($checksum%10)==0)?true:false;
}
//checkvarIoUscreditcardnumbers:
$nums=array(
'344234534664577'=>'a','3794234534664577'=>'a','4938748398324'=>'v','4123-1234-5342'=>'v','5184729384567434'=>'m','5723x2345x2345x6161'=>'m','6011601160116011'=>'d','6012392563242423'=>'d',);
foreach($numsas$num=>$type){
$st=standardize_credit($num);
$valid=validate_credit($st,$type);
$output=$valid?'valid':'invalid';
echo<p>{$st}-{$type}={$output}</p>\n;
}
/***   来自编程之家 jb51.cc(jb51.cc)   ***/

 

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...