首頁  >  問答  >  主體

為什麼我的驗證碼只顯示一個數字?

//這堂課我的程式碼是這樣的,我檢查了幾遍,沒看出有什麼錯誤,但是顯示出來的驗證碼只有一個數字...為什麼會這樣,求各位大神指導


<?php

//產生驗證碼的背景

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

//背景圖的尺寸

$width=60;

#$height=15;

//建立畫布

$ img=imagecreatetruecolor($width, $height);

//分配顏色

$white=imagecolorallocate($img, 0xff, 0xff, 0xff);

//填滿顏色到畫布

imagefill($img, 0, 0, $white);

//產生驗證碼的值

$chars='1234567890';

$chars_len=strlen($chars);

$code_len=4;//驗證碼長度

$code="";//初始值

#for ($i=1; $i < $code_len; $i) { 

$rand=mt_rand(0,$chars_len-1);//隨機取出四個數字

$code=$rand;//將取出的數字連接在一起

}

//存入session中,用驗證

session_start();

$_SESSION['ver_code']=$code;

//隨機分配字串顏色

$str_color=imagecolorallocate($img, mt_rand(0,255),  mt_rand( 0,255),  mt_rand(0,255));

//計算字串居中顯示

//字串的大小

$font=5;

//畫布尺寸

$img_w=imagesx($img);

$img_h=imagesy($img);

//字體尺寸

$font_w=imagefontwidth($font);

$font_h=imagefontheight($font);

//字串尺寸

$code_w=$font_w*$code_len ;

$code_h=$font_h;

$x=($img_w-$code_w)/2;

$y=($img_h-$code_h)/2 ;

//把驗證碼輸出到畫布上

imagestring($img, $font, $x, $y, $code, $str_color);

/ /直接輸出

imagejpeg($img);

imagedestroy($img);


?>


丫头丫头2345 天前2977

全部回覆(5)我來回復

  • 王承毅

    王承毅2018-04-21 12:33:36

    for($i=0;$i<$code_len;$i++){

    $rand=mt_rand(0,$chars_len-1);//隨機取出數字

    # $code.=$rand; //將取出的四位數拼接在一起

    }

    你少了個連接符號

    回覆
    0
  • 丫头

    可以了哎,謝謝哈

    丫头 · 2018-04-22 10:53:02
  • 丫头

    丫头2018-04-21 11:28:11

    <?php

    //產生驗證碼的背景

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

    //背景圖的尺寸

    $width=60;

    $height=15;

    //建立畫布

    $img=imagecreatetruecolor($width, $height) ;

    //分配顏色

    $white=imagecolorallocate($img, 0xff, 0xff, 0xff);

    //填滿顏色到畫布

    # imagefill($img, 0, 0, $white);

    //產生驗證碼的值

    $chars='1234567890';

    $chars_len=strlen( $chars);

    $code_len=4;//驗證碼長度

    $code="";//初始值

    for ($i=1; $ i < $code_len; ++$i) { 

    $rand=mt_rand(0,$chars_len-1);//隨機取出四個數字

    $code.=$rand ;//將取出的數字連接在一起

    }

    //存入session中,用驗證

    session_start();

    $_SESSION ['ver_code']=$code;

    //隨機分配字串顏色

    $str_color=imagecolorallocate($img, mt_rand(0,255),  mt_rand(0,255),  mt_rand(0,255) );

    //計算字串居中顯示

    //字串的大小

    #$font=5;

    //畫布尺寸

    $img_w=imagesx($img);

    $img_h=imagesy($img);

    //字體尺寸

    $font_w=imagefontwidth($ font);

    $font_h=imagefontheight($font);

    //字串尺寸

    $code_w=$font_w*$code_len;

    $code_h=$font_h;

    $x=($img_w-$code_w)/2;

    $y=($img_h-$code_h)/2;

    //把驗證碼輸出到畫布上

    imagestring($img, $font,$x.$y.$code,$str_color);

    //直接輸出

    ##imagejpeg($img);

    imagedestroy($img);


    ?>


    ###

    回覆
    0
  • 丫头

    丫头2018-04-21 11:21:00

    TIM图片20180421112016.png

    改成這樣之後就會變成3個數字了...

    回覆
    1
  • 王承毅

    你for循環出錯了,應該是這樣的。 for($i=0;$i<$code_len;$i++){ $rand=mt_rand(0,$chars_len-1);//隨機取出數字 $code.=$rand; //將取出的四位數字拼接在一起 }

    王承毅 · 2018-04-21 12:35:29
  • 取消回覆