加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

php 验证信用卡卡号的简单示例

发布时间:2020-05-25 05:19:41 所属栏目:PHP 来源:互联网
导读:php 验证信用卡卡号的简单示例

对php验证信用卡卡号代码感兴趣的小伙伴,下面一起跟随脚本之家 jb51.cc的小编两巴掌来看看吧!
php验证信用卡卡号代码,可以用来验证普通信用卡,visa,master等信用卡,采用了Luhn算法


/**
 * php验证信用卡卡号代码
 *
 * @param 
 * @arrange 512-笔记网: www.www.jb51.cc
 **/
// This function will take a credit card number and check to make sure it
// contains the right amount of digits and uses the Luhn Algorithm to
// weed out made up numbers
function validateCreditcard_number($credit_card_number)
{
	// Get the first digit
	$firstnumber = substr($credit_card_number,1);
	// Make sure it is the correct amount of digits. Account for dashes being present.
	switch ($firstnumber)
	{
		case 3:
			if (!preg_match('/^3d{3}[ -]?d{6}[ -]?d{5}$/',$credit_card_number))
			{
				return 'This is not a valid American Express card number';
			}
			break;
		case 4:
			if (!preg_match('/^4d{3}[ -]?d{4}[ -]?d{4}[ -]?d{4}$/',$credit_card_number))
			{
				return 'This is not a valid Visa card number';
			}
			break;
		case 5:
			if (!preg_match('/^5d{3}[ -]?d{4}[ -]?d{4}[ -]?d{4}$/',$credit_card_number))
			{
				return 'This is not a valid MasterCard card number';
			}
			break;
		case 6:
			if (!preg_match('/^6011[ -]?d{4}[ -]?d{4}[ -]?d{4}$/',$credit_card_number))
			{
				return 'This is not a valid Discover card number';
			}
			break;
		default:
			return 'This is not a valid credit card number';
	}
	// Here's where we use the Luhn Algorithm
	$credit_card_number = str_replace('-','',$credit_card_number);
	$map = array(0,1,2,3,4,5,6,7,8,9,9);
	$sum = 0;
	$last = strlen($credit_card_number) - 1;
	for ($i = 0; $i <= $last; $i++)
	{
		$sum += $map[$credit_card_number[$last - $i] + ($i & 1) * 10];
	}
	if ($sum % 10 != 0)
	{
		return 'This is not a valid credit card number';
	}
	// If we made it this far the credit card number is in a valid format
	return 'This is a valid credit card number';
}
echo validateCreditcard_number('4111-1111-1111-1111'); // This is a valid credit card number
echo validateCreditcard_number('4111-1111-1111-1112'); // This is not a valid credit card number
echo validateCreditcard_number('5558-545f-1234');      // This is not a valid MasterCard card number
echo validateCreditcard_number('9876-5432-1012-3456'); // This is not a valid credit card number
/***   来自脚本之家 jb51.cc(jb51.cc)   ***/

 

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读