之前帮朋友写过一个,他们使用了一个在网上找的验证码生成程序,估计用的人太多了,竟然没防住。我个人比较喜欢JS去解决问题,最终使用本方案之后,就没有再出问题。
==================================================================
#= 使用说明:http://www.17sohu.com/products/tokencode/last.zip =
#= 演示地址:http://www.17sohu.com/products/tokencode/ =
#= 使用说明:http://www.17sohu.com/p/tokencode =
#=====================================================================
class TokenCode {
public $value, $code ;
public $OperationList;
public function __construct() {
$resultValue = $this -> RandomKey($this -> RandomIntger());
$resultCode = "'" . $resultValue . "'";
$this -> OperationList = Array("+", "-" ,"*");
for( $i = 0 ; $i < $this -> RandomIntger() + 3; $i++){
$op = $this -> RandOperation();
switch($op){
case "+":
case "-":
$random = $this -> RandEquations();
$resultValue .= $random["value"];
$resultCode .= "+(" . $random["code"] . ")";
break;
default:
$random = $this -> RandomKey($this -> RandomIntger());
$resultValue .= $random;
$resultCode .= "+'" . $random . "'";
break;
}
}
$rnd1 = $this -> RandomIntger();
$rnd2 = $this -> RandomIntger() + 8;
$this -> value = substr($resultValue, $rnd1, $rnd2);
$this -> code = "(" . $resultCode . ").substring(" . $rnd1 . "," . ($rnd1 + $rnd2) . ")";
}
private function RandEquations(){
$va = $str = $this -> RandomLong();
$this -> OperationList = Array("+", "-" ,"*");
for( $i = 0 ; $i < $this -> RandomIntger(); $i++){
$op = $this -> RandOperation();
$vb = $this -> RandomLong();
switch($op){
case "+":
$va += $vb;
$str .= "+" . $vb;
break;
case "-":
$va -= $vb;
$str .= "-" . $vb;
break;
case "*":
$va *= $vb;
$str = "(" . $str . ")*" . $vb;
break;
}
}
return Array(
"code" => $str,
"value" => $va
);
}
private function RandOperation(){
return $this -> OperationList[rand() % count($this -> OperationList)];
}
private function RandomIntger(){
return (int)substr(rand(), 1, 1) + 1;
}
private function RandomLong(){
return (int)substr(rand(), 1, 3) + 1;
}
private function RandomKey($len = 10){
return substr(md5(rand()), 1, $len + 5);
}
}
?>
调用方法:
require("TokenCode.php");
$token = new TokenCode();
$tokenValue = $token -> value ;
$tokenCode = $token -> code ;
//代码段
$_SESSION["_TOKENCODE"] = $token -> value ;
//代码段
echo '';
?>
保存好session后,到验证页验证提交的code和验证结果即可,程序改动非常少,只需要js改动一下即可。
#AJAX方式
$.post("/", {mob : $("#mob").val() , token : _TOKENCODE }, function(){ } );
#URL方式
$("#send").click(function(){
if(this.href.indexOf('&token=')==-1){
this.href+='&token=' + _TOKENCODE
};
});