Php 未初始化字符串偏移量:62

Php 未初始化字符串偏移量:62,php,gd,Php,Gd,所以我正处于尝试做一些验证码的早期阶段 到目前为止,我的图像生成代码: session_start(); header('Content-type: image/jpeg'); $string = $_SESSION['secure']; $font_size = 5; $image_width = ImageFontWidth($font_size)*strlen($string); $image_height = ImageFontHeight($font_size); $image =

所以我正处于尝试做一些验证码的早期阶段

到目前为止,我的图像生成代码:

session_start();
header('Content-type: image/jpeg');

$string = $_SESSION['secure'];
$font_size = 5;
$image_width = ImageFontWidth($font_size)*strlen($string);
$image_height = ImageFontHeight($font_size);

$image = imagecreate($image_width, $image_height);
imagecolorallocate($image, 255, 255, 255);
$font_colour = imagecolorallocate($image, 0, 0, 0);

imagestring($image, $font_size, 0, 0, $string, $font_colour);
imagejpeg($image);
表单本身的代码(函数在单独的文件(rand.php)中):

函数随机字符串($length=10){
$alphnum='0123456789abcdefghijklmnopqrstuvwxyzabefghijklmnopqrstuvxyz';
$alphnum_length=strlen($alphnum);
$random_string='';
对于($i=0;$i<$length;$i++){
$random_string.=$alphnum[rand(0,$alphnum_长度)];
}
返回$random_字符串;
}
需要('../rand.php');
$\u SESSION['secure']=随机字符串(5);
echo$_会话['secure'];
现在它生成一个随机字符串,在generate image页面上确实生成了一个图像。我还没有在表单页面上输出图像,但这不是问题所在

问题是每隔20次左右刷新表单页面(当前仅输出随机字符串的页面),我会收到一个错误,说明:

(!)注意:第10行C:Sandbox\gd\rand.php中的未初始化字符串偏移量:62

我得到这个错误,而不是通常的5个字符长度的字符串,我只得到4


我是个新手,所以我没有必要的资金自己调试这个。请您提供一些建议好吗?

问题是,“Z”是索引61,而不是62(字符串的长度),因为php中的数组以索引0开头。让我们来看看代码:

<?php

// [...]
function random_string($length = 10){
$alphnum = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// $alphnum_length will contain 62
$alphnum_length = strlen($alphnum);

//[...]
    // the rand function will produce random numbers between 0 and 62 
    // (0 <= random number <= 62)
    // but the biggest index is just 61
    $random_string.= $alphnum[rand(0, $alphnum_length)];
// [...]
}

或者,如果您想要更高的性能(非常小),请更换


但不是两者都有;)

问题是,“Z”是索引61,而不是62(字符串的长度),因为php中的数组以索引0开头。让我们来看看代码:

<?php

// [...]
function random_string($length = 10){
$alphnum = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// $alphnum_length will contain 62
$alphnum_length = strlen($alphnum);

//[...]
    // the rand function will produce random numbers between 0 and 62 
    // (0 <= random number <= 62)
    // but the biggest index is just 61
    $random_string.= $alphnum[rand(0, $alphnum_length)];
// [...]
}

或者,如果您想要更高的性能(非常小),请更换

但不是两者都有;)

rand
范围包括在内。萨皮恩蒂(Sapienti sat;)<代码>兰德范围包括在内。萨皮恩蒂(Sapienti sat;)
$random_string.= $alphnum[rand(0, $alphnum_length)];
$random_string.= $alphnum[rand(0, $alphnum_length - 1)];
$alphnum_length = strlen($alphnum);
$alphnum_length = strlen($alphnum) - 1;