https://github.com/emotionLoop/visualCaptcha 服务器端(php) demo是基于slim框架进行开发,如果项目用的slim框架开发应该很容易, 因为我的代码不是基于这个框架,所以我读了下他的代码,希望对读者有帮助。 基本流程就是
1.ajax请求 /start返回显示验证码的信息
请求验证码的代码
session_start();
/** @var \visualCaptcha\Session $session */
$session = new \visualCaptcha\Session();
$howMany = 6;
$captcha = new \visualCaptcha\Captcha($session);
$captcha->generate($howMany);
$this->RESP
->setHeader('Content-Type', 'text/json; charset=utf-8')
->setBody(
json_encode(
$captcha->getFrontEndData(),
JSON_UNESCAPED_UNICODE)
);
RESP是符合psr7 response的对象负责输出数据。
2.请求生成图片数据
session_start();
$params = $this->REQ->getQueryParams();
$index = $params["index"];
$session = new \visualCaptcha\Session();
$captcha = new \visualCaptcha\Captcha($session);
$this->RESP->setHeader('Content-Type', 'image/png');
$captcha->streamImage([], $index, false);
REQ是符合psr7 request的对象负责获取request数据。
$this->RESP->setHeader('Content-Type', 'image/png');//设置mime格式
可以通过查看类库源码了解输出图片原理
// Stream image file given an index in the session visualCaptcha images array
// @param headers object. used to store http headers for streaming
// @param index of the image in the session images array to send
// @paran isRetina boolean. Defaults to false
public function streamImage( $headers, $index, $isRetina ) {
$imageOption = $this->getImageOptionAtIndex( $index );
$imageFileName = $imageOption ? $imageOption[ 'path' ] : ''; // If there's no imageOption, we set the file name as empty
$imageFilePath = $this->assetsPath . '/images/' . $imageFileName;
// Force boolean for isRetina
$isRetina = intval( $isRetina ) >= 1;
// If retina is requested, change the file name
if ( $isRetina ) {
$imageFileName = preg_replace( '/\.png/i', '@2x.png', $imageFileName );
$imageFilePath = preg_replace( '/\.png/i', '@2x.png', $imageFilePath );
}
// If the index is non-existent, the file name will be empty, same as if the options weren't generated
if ( !empty( $imageFileName ) ) {
return $this->utilStreamFile( $headers, $imageFilePath );
}
return false;
}
#不过我没看出来header有什么作用,所有我只给一个空数组
// Set the appropriate mime type
$headers[ 'Content-Type' ] = $mimeType;
// Make sure this is not cached
$headers[ 'Cache-Control' ] = 'no-cache, no-store, must-revalidate';
$headers[ 'Pragma' ] = 'no-cache';
$headers[ 'Expires' ] = 0;
readfile( $filePath );
retina是设置图片大小。 3.数据上传进行验证
session_start();
$params = $REQ->getQueryParams();
$session = new \visualCaptcha\Session();
$captcha = new \visualCaptcha\Captcha($session);
$frontendData = $captcha->getFrontendData();
if ($imageAnswer = $params[ $frontendData['imageFieldName'] ] ) {
if ($captcha->validateImage($imageAnswer)) {
return true;
} else {
return false;
}
}