gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 21:18:40 34 4
gpt4 key购买 nike

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

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

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'];

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

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

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

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

我是个新手,所以我没有足够的资金来自己调试它。请问您能提供一些建议吗?

最佳答案

问题是,'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;

但不是两者都;)

关于php - 未初始化的字符串偏移量: 62,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29059668/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com