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


Uninitialized string offset: 62

所以我正处于尝试制作一个小验证码作为练习的早期阶段。

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

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)中):

function random_string($length = 10){
    $alphnum = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $alphnum_length = strlen($alphnum);
    $random_string = '';
    for ($i=0; $i < $length; $i++) { 
        $random_string.= $alphnum[rand(0, $alphnum_length)];
    }
    return $random_string;
}
require('../rand.php'); 
$_SESSION['secure'] = random_string(5);
echo $_SESSION['secure'];

现在它生成一个随机字符串,并且在生成图像页面上确实生成了一个图像。我还没有在表单页面上输出图像,但这不是问题。

问题是表单页面(当前仅输出random_string的页面)每 20 次左右刷新一次,我会收到一条错误消息,指出:

( !注意:未初始化的字符串偏移量:C:Sandbox''gd''rand.php 第 10 行中的 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)];
// [...]
}

所以你必须更换任何一个

$random_string.= $alphnum[rand(0, $alphnum_length)];

$random_string.= $alphnum[rand(0, $alphnum_length - 1)];

或者,如果您想要更高的性能(很少)

替换
$alphnum_length = strlen($alphnum);

$alphnum_length = strlen($alphnum) - 1;

但并非两者都;)