随机生成验证码
<?php
/*
打乱字符串:str_shuffle
提取子串:substr
产生一个0-9的数组:range(0, 9)
打乱数组:shuffle
数组合并:array_merge()
数组键值对调:array_flip
数组中提取子数组:array_slice
数组中元素执行回调函数:array_map
数字转化为ascii:chr ord
不区分大小写字符串比较:strcasecmp
*/
//产生随机数字字符串
function rand_number($num)
{
/*
$str = '0123456789';
return substr(str_shuffle($str), 0, $num);*/
$arr = range(0, 9);
shuffle($arr);
$arr1 = array_slice($arr, 0, $num);
return join('', $arr1);
/*
$str = join('', $arr);
return substr(str_shuffle($str), 0, $num);*/
}
//echo rand_number(4);
//产生随机大小写字母字符串
function rand_char($num)
{
/*
$str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$str_shu = str_shuffle($str);
return substr($str_shu, 0, $num);*/
/*
$arr1 = range('a', 'z');
$arr2 = range('A', 'Z');
$arr = array_merge($arr1, $arr2);
shuffle($arr);
$result = array_slice($arr, 0, $num);
return join('', $result);*/
$arr1 = range('a', 'z');
$arr2 = range('A', 'Z');
$arr = array_merge($arr1, $arr2);
$arr3 = array_flip($arr);
$result = array_rand($arr3, $num);
return join('', $result);
}
//echo rand_char(4);
function rand_num_char($num)
{
/*
$arr = range('a', 'z');
$str = join('', $arr);
$str .= strtoupper($str);
$str .= join('', range(0, 9));
return substr(str_shuffle($str), 0, $num);*/
$str = '';
for ($i = 0; $i < $num; $i++) {
$rand = mt_rand(0, 2);
switch ($rand) {
case 0:
$str .= chr(mt_rand(48, 57));
break;
case 1:
$str .= chr(mt_rand(97, 122));
break;
case 2:
$str .= chr(mt_rand(65, 90));
break;
}
}
return $str;
}
//echo rand_num_char(4);
// 1-9 + - * 1-9 3+5=
function rand_compute()
{
$a = mt_rand(1, 9);
$b = mt_rand(1, 9);
$arr = ['+', '-', '*'];
$rand = mt_rand(0, 2);
return $a.$arr[$rand].$b.'=';
}
echo rand_compute();
1、验证码
1、纯数字
2、纯字母
3、数字字母混合
4、计算公式 3 + 5 =
打乱字符串:str_shuffle
提取子串:substr
产生一个0-9的数组:range(0, 9)
打乱数组:shuffle
数组合并:array_merge()
数组键值对调:array_flip
数组中提取子数组:array_slice
数组中元素执行回调函数:array_map
数字转化为ascii:chr ord
不区分大小写字符串比较:strcasecmp
2、水印
3、缩放
思考:
这个switch case是否可以优化?
function kidOfImage($srcImg, $size, $imgInfo){
//传入新的尺寸,创建一个指定尺寸的图片
$newImg = imagecreatetruecolor($size['old_w'], $size['old_h']);
//定义透明色
$otsc = imagecolortransparent($srcImg);
if( $otsc >= 0) {
//取得透明色
$transparentcolor = imagecolorsforindex( $srcImg, $otsc );
//创建透明色
$newtransparentcolor = imagecolorallocate(
$newImg,
$transparentcolor['red'],
$transparentcolor['green'],
$transparentcolor['blue']
);
} else {
$newtransparentcolor = imagecolorallocate($newImg, 0, 0, 0);
}
//背景填充透明
imagefill( $newImg, 0, 0, $newtransparentcolor );
imagecolortransparent($newImg, $newtransparentcolor);
imagecopyresized( $newImg, $srcImg, $size['x'], $size['y'], 0, 0, $size["new_w"], $size["new_h"], $imgInfo["width"], $imgInfo["height"] );
return $newImg;
}