当前位置: 首页 > 编程文章 >

PHP实现通用的信用卡验证类

PHP实现通用的信用卡验证类

作者:沈宁时间:2026-05-03 12:26:15浏览:744

本文介绍了一个基于PHP的通用信用卡验证解决方案,版本为3.5。该方案通过四步流程确保信用卡号码输入的准确性,支持American Express、Visa、MasterCard等主流卡种。文章提供了详细的安装说明及完整的PHP代码实现,帮助开发者快速集成信用卡校验功能。

本文目录展开

PHP信用卡验证类概述

本实例详细解析了如何使用PHP构建一个通用的信用卡验证类,旨在为开发者提供参考与借鉴。

相关背景信息如下:

Credit Card Validation Solution (PHP Edition) Version 3.5 Description Credit Card Validation Solution™ uses a four step process to ensure credit card numbers are keyed in correctly. This procedure accurately checks cards from American Express, Australian BankCard, Carte Blache, Diners Club, Discover/Novus, JCB, MasterCard and Visa. For more information, please read the comments in the code itself. Installation Instructions Select the text between the two lines indicated, below. Copy the text. Open up a text editor. Paste the text. Save that file. When saving it, make sure to: save it in a directory on your webserver, and name it with an extension that your server will recognize needs parsing by PHP. To see it in action, open up that file in your web browswer.

核心代码实现如下:


<?php
# ------------------------------------------------------------------------
# Credit Card Validation Solution, version 3.5         PHP Edition
# 25 May 2000
#
# COPYRIGHT NOTICE:
# a) This code is property of The Analysis and Solutions Company.
# b) It is being distributed free of charge and on an "as is" basis.
# c) Use of this code, or any part thereof, is contingent upon leaving
#   this copyright notice, name and address information in tact.
# d) Written permission must be obtained from us before this code, or any
#   part thereof, is sold or used in a product which is sold.
# e) By using this code, you accept full responsibility for its use
#   and will not hold the Analysis and Solutions Company, its employees
#   or officers liable for damages of any sort.
# f) This code is not to be used for illegal purposes.
# g) Please email us any revisions made to this code.
#
# Copyright 2000         http://www.AnalysisAndSolutions.com/code/
# The Analysis and Solutions Company     info@AnalysisAndSolutions.com
# ------------------------------------------------------------------------
#
# DESCRIPTION:
# Credit Card Validation Solution uses a four step process to ensure
# credit card numbers are keyed in correctly. This procedure accurately
# checks cards from American Express, Australian BankCard, Carte Blache,
# Diners Club, Discover/Novus, JCB, MasterCard and Visa.
#
# CAUTION:
# CCVS uses exact number ranges as part of the validation process. These
# ranges are current as of 20 October 1999. If presently undefined ranges
# come into use in the future, this program will improperly deject card
# numbers in such ranges, rendering an error message entitled "Potential
# Card Type Discrepancy." If this happens while entering a card & type
# you KNOW are valid, please contact us so we can update the ranges.
#
# POTENTIAL CUSTOMIZATIONS:
# * If you don't accept some of these card types, edit Step 2, using pound
# signs "#" to comment out the "elseif," "$CardName" and "$ShouldLength"
# lines in question.
# * Additional card types can be added by inserting new "elseif,"
# "$CardName" and "$ShouldLength" lines in Step 2.
# * The three functions here can be called by other PHP documents to check
# any number.
#
# CREDITS:
# We learned of the Mod 10 Algorithm in some Perl code, entitled
# "The Validator," available on Matt's Script Archive,
# http://worldwidemart.com/scripts/readme/ccver.shtml. That code was
# written by David Paris, who based it on material Melvyn Myers reposted
# from an unknown author. Paris credits Aries Solis for tracking down the
# data underlying the algorithm. At the same time, our code bears no
# resemblance to its predecessors. CCValidationSolution was first written
# for Visual Basic, on which Allen Browne and Rico Zschau assisted.
# Neil Fraser helped prune down the OnlyNumericSolution() for Perl.
function CCValidationSolution ($Number) {
    global $CardName;
    # 1) Get rid of spaces and non-numeric characters.
    $Number = OnlyNumericSolution($Number);
    # 2) Do the first four digits fit within proper ranges?
    #   If so, who's the card issuer and how long should the number be?
    $NumberLeft = substr($Number, 0, 4);
    $NumberLength = strlen($Number);
    if ($NumberLeft >= 3000 and $NumberLeft <= 3059) {
        $CardName = "Diners Club";
        $ShouldLength = 14;
    } elseif ($NumberLeft >= 3600 and $NumberLeft <= 3699) {
        $CardName = "Diners Club";
        $ShouldLength = 14;
    } elseif ($NumberLeft >= 3800 and $NumberLeft <= 3889) {
        $CardName = "Diners Club";
        $ShouldLength = 14;
    } elseif ($NumberLeft >= 3400 and $NumberLeft <= 3499) {
        $CardName = "American Express";
        $ShouldLength = 15;
    } elseif ($NumberLeft >= 3700 and $NumberLeft <= 3799) {
        $CardName = "American Express";
        $ShouldLength = 15;
    } elseif ($NumberLeft >= 3528 and $NumberLeft <= 3589) {
        $CardName = "JCB";
        $ShouldLength = 16;
    } elseif ($NumberLeft >= 3890 and $NumberLeft <= 3899) {
        $CardName = "Carte Blache";
        $ShouldLength = 14;
    } elseif ($NumberLeft >= 4000 and $NumberLeft <= 4999) {
        $CardName = "Visa";
        if ($NumberLength > 14) {
            $ShouldLength = 16;
        } elseif ($NumberLength < 14) {
            $ShouldLength = 13;
        } else {
            echo "
            <em>The Visa number entered, $Number, in is 14 digits long.
            Visa cards usually have 16 digits, though some have 13.
            Please check the number and try again.</em>
            n";
            return FALSE;
        }
    } elseif ($NumberLeft >= 5100 and $NumberLeft <= 5599) {
        $CardName = "MasterCard";
        $ShouldLength = 16;
    } elseif ($NumberLeft == 5610) {
        $CardName = "Australian BankCard";
        $ShouldLength = 16;
    } elseif ($NumberLeft == 6011) {
        $CardName = "Discover/Novus";
        $ShouldLength = 16;
    } else {
        echo "
        <em>The first four digits of the number entered are $NumberLeft.
        If that's correct, we don't accept that type of credit card.
        If it's wrong, please try again.</em>
        n";
        return FALSE;
    }
    # 3) Is the number the right length?
    if ($NumberLength <> $ShouldLength) {
        $Missing = $NumberLength - $ShouldLength;
        if ($Missing < 0) {
            echo "
            <em>The $CardName number entered, $Number, is missing " . abs($Missing) . " digit(s).
            Please check the number and try again.</em>
            n";
        } else {
            echo "
            <em>The $CardName number entered, $Number, has $Missing too many digit(s).
            Please check the number and try again.</em>
            n";
        }
        return FALSE;
    }
    # 4) Does the number pass the Mod 10 Algorithm Checksum?
    if (Mod10Solution($Number) == TRUE) {
        return TRUE;
    } else {
        echo "
        <em>The $CardName number entered, $Number, is invalid.
        Please check the number and try again.</em>
        n";
        return FALSE;
    }
}
function OnlyNumericSolution ($Number) {
    # Remove any non numeric characters.
    # Ensure number is no more than 19 characters long.
    return substr( ereg_replace( "[^0-9]", "", $Number) , 0, 19);
}
function Mod10Solution ($Number) {
    $NumberLength = strlen($Number);
    $Checksum = 0;
    # Add even digits in even length strings
    # or odd digits in odd length strings.
    for ($Location = 1 - ($NumberLength % 2); $Location < $NumberLength; $Location += 2) {
        $Checksum += substr($Number, $Location, 1);
    }
    # Analyze odd digits in even length strings
    # or even digits in odd length strings.
    for ($Location = ($NumberLength % 2); $Location < $NumberLength; $Location += 2) {
        $Digit = substr($Number, $Location, 1) * 2;
        if ($Digit < 10) {
            $Checksum += $Digit;
        } else {
            $Checksum += $Digit - 9;
        }
    }
    # Is the checksum divisible by ten?
    return ($Checksum % 10 == 0);
}
# ----------- BEGIN SAMPLE USER INTERFACE SECTION ------------
#
# This section provides a simple sample user interface for the
# Credit Card Validation functions. It generates an HTML form
# where you enter a card number to check.
#
# If a number has been posted by the form, check it.
if ( isset($Number) ) {
    # Get rid of spaces and non-numeric characters in posted
    # numbers so they display correctly on the input form.
    $Number = OnlyNumericSolution($Number);
    if (CCValidationSolution($Number) == TRUE) {
        echo "
        The $CardName number entered, $Number, <em>is</em> valid.
        n";
    }
} else {
    $Number = "";
}
# Setup an input form. Posting it calls this page again.
echo "<form method="post" action="$REQUEST_URI">n";
echo "
Credit Card Number: <input type="text" name="Number" value="$Number">n";
echo "<input type="Submit" name="submitr" value="Check its Validity">n";
echo "</form>
n";
#
# ------------ END SAMPLE USER INTERFACE SECTION -------------
?>

期望上述内容能对您的PHP编程实践提供有益帮助。

上一篇
PHP使用glob函数遍历目录或文件夹的方法

本文介绍PHP中利用glob函数简洁遍历目录及匹配文件路径的方法,并提供具体代码示例。同时对比传统的opendir与readdir组合实现方式,分析两者在代码简洁度与功能上的差异,推荐在实际开发中使用glob函数以提高效率。

下一篇
PHP通过读取文件前几个字节判断上传文件类型

本文介绍一种基于读取文件前几个字节来判断上传文件类型的PHP方法。该方法通过fopen和fread读取文件头部数据,利用unpack解析二进制字符码,并根据特定的数值组合(如JPG的-119, 80或PNG的-119, 80等)匹配对应的文件扩展名,从而在服务器端验证文件真实性,防止恶意文件上传。

相关文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,031
PHP操作MySQL数据库:从工具选择到实战案例

本文介绍了使用PHP操作MySQL数据库的完整流程,涵盖命令行、Navicat及phpMyAdmin等常用管理工具。重点讲解HTTP GET与POST方式在表单数据传递中的区别与安全特性。通过mysqli扩展的基础步骤(创建连接、选择库、设置编码、执行SQL、关闭连接),演示了增删改查的具体实现,并对比了fetch_assoc、fetch_row和fetch_array三种结果集获取方法的差异。最后结合注册与登录两个实际案例,展示如何将前端用户输入安全地存入数据库并进行验证。

2026.01.07 1,004
PHP中self、$this、const与static关键字的使用详解

本文详细解析PHP类中self、$this、const及static关键字的正确用法。重点说明静态方法仅能访问静态或常量属性,实例方法通过$this访问非静态属性,并纠正const定义无需美元符号的常见误区,帮助开发者避免作用域混淆错误。

2025.05.10 1,001
PHP与Node.js深度对比:十轮较量后的选择建议

在服务器端开发语言选择日益多样化的背景下,PHP与Node.js成为开发者关注的焦点。本文通过起步难度、生态系统、语法特性、工具链、部署环境等十个维度对两者进行逐轮对比。结果显示Node.js在性能、全栈统一及现代开发体验上胜出,而PHP在易学性、托管便利性及成熟度上保持优势。最终建议开发者根据项目需求和个人技能树做出理性选择,而非盲目追随潮流。

2025.03.29 1,001
PHP递归扫描目录打印所有JPG文件名及超时处理

本文介绍使用PHP函数递归扫描指定目录及其子目录下所有JPG文件名的方法。针对本地测试中因图片数量庞大(几十GB)导致运行超时的情况,建议在实际应用中考虑分批处理或增加执行时间限制,以确保脚本稳定运行并高效输出目标文件列表。

2026.07.09 1,000
LINUX下PHP程序实现WORD文件转化为PDF文件的方法

本文介绍在LINUX环境下通过PHP程序将Word文件转换为PDF文件的具体实现方法。文中提供了相关的代码示例及参考链接,旨在帮助开发者解决文件格式转换需求,提升文档处理效率。

2026.11.12 999

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。