1.簡介
最近有個需求,就是把圖片驗證碼轉化為base64格式,tp5框架自帶的think-captcha擴展包可以實作,但是,它有個缺點,不能獲取驗證碼的值,在做前后端分離專案的時候,驗證碼檢測有兩種方式,各有利弊,
方式一:因為session不能共享,所以通過傳遞唯一uuid,后端用redis存盤uuid對應的驗證碼,驗證同理,
方式二:直接回傳驗證碼的同時,把驗證值也回傳給前端,在前端去驗證驗證碼的有效性
下面不多說,看代碼,(如果你還有第三種方法,歡迎留言,共同學習)
2.代碼片段
$width = 100;
$height = 30;
$size = 4;
$fontSize = 10;
$image = imagecreatetruecolor((int)$width, (int)$height);
$bgcolor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgcolor);
$content = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
$captcha = "";
for ($i = 0; $i < $size; $i++) {
$fontsize = $fontSize;
$fontcolor = imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
$fontcontent = substr($content, mt_rand(0, strlen($content)), 1);
$captcha .= $fontcontent;
$x = ($i * $width / 4) + mt_rand(5, 10);
$y = mt_rand(5, 10);
imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);
}
imagepng($image);
$content = ob_get_clean();
imagedestroy($image);
$base64 = 'data:image/png;base64,' . base64_encode($content);
return json_encode(['code' => 0, 'data' => ['base64' => $base64, 'text' => $captcha], 'message' => '操作成功']);
本文來自博客園,作者:淙淙溪流,轉載請注明原文鏈接:https://www.cnblogs.com/pitmanhuang/p/16199473.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/465977.html
標籤:其他
下一篇:const關鍵字:可改不可改?
