简体   繁体   中英

Uninitialized string offset: 62

So I'm in the early stages of trying to make a little captcha thing as practise.

My code thus far, for the image generation:

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);

And the code for the form itself (function is in separate file (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'];

Now it generates a random string, and on the generate image page an image is indeed generated. I've not yet gotten to outputting the image on the form page but thats not the issue.

The issue is every 20 or so refreshes of the form page (the page thats only currently outputting the random_string) I get an error stating:

( ! ) Notice: Uninitialized string offset: 62 in C:Sandbox\\gd\\rand.php on line 10

I get this error, and instead of the usual 5 character length string I only get 4.

I'm fairly new so I've not the wherewithal to debug this myself. Please could you offer some advice?

The problem is, that 'Z' is index 61 and not 62 (the length of the string), because arrays in php starts with index 0. So let 's go to the code:

<?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)];
// [...]
}

So you have to replace either

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

with

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

or if you want a little more performance (a very little) replace

$alphnum_length = strlen($alphnum);

with

$alphnum_length = strlen($alphnum) - 1;

BUT NOT both ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM