这篇文章主要为大家详细介绍了《php 5 in practice中文版》里提供的信用卡验证示例,具有一定的参考价值,可以用来参考一下。
对《php 5 in practice中文版》里提供的信用卡验证php代码感兴趣的小伙伴,下面一起跟随四海网的小编两巴掌来看看吧!
/**
* 《php 5 in practice中文版》里提供的信用卡验证php代码
*
* @param
* @arrange 512-笔记网: q1010.com
**/
<?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,0,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,0,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";
}
/*** 来自四海网(www.q1010.com) ***/
本文来自:http://www.q1010.com/173/847-0.html
注:关于《php 5 in practice中文版》里提供的信用卡验证示例的内容就先介绍到这里,更多相关文章的可以留意四海网的其他信息。
关键词:信用卡
四海网收集整理一些常用的php代码,JS代码,数据库mysql等技术文章。